• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Simple Perl Question

BChico

Platinum Member
I am just starting to learn Perl, so I dont even know if this quesiton makes sense.

If I have an input file that looks like this:

Alpha
Test
Test

Beta
Test
Test

What is the easiest way to have it print only the data assoicated with Alpha? When I try to use something similar to this $_ =~ /\\Alpha\\/ it will only print the line with Alpha on it obviously. Is there a way to tell Perl to print following lines?
 
You'll pretty much have to loop over each line and decide what to print and what not to print. Using a carriage return as your delimiter isn't the best idea but it'll work.

If you just want to mess around with regex's you can probably come up with a regex to print them all since you can match on \n or \r but it would probably be pretty ugly for little gain other than just sayin "Look what I did!". =) And if that's the case you might want to get something like visual-regex so you can mess around with the regex and see what it matches in real-time.
 
Print after you see alpha - stop when you see a new heading (in this case, beta). If your file is set up like this (uniform pattern, no surprises) this should be cake.
 
#!/usr/bin/perl

open(FH, "file.txt");
my $flag = 0;

while (<FH>) {
. $flag = 1 if (/^Alpha$/);
. $flag = 0 if (/^$/);
. print if ($flag);
}

Remove the periods, they're just for indenting for the forum. This assumes you have a blank line between each set of data.
 
Remember, one of the philosophies behind perl is TMTOWTDI. You could write the same code in a more traditional C-ish fashion, not exploiting $_ or the <blank> if <blank> syntax. It's all about what's most comfortable for you.
 
Originally posted by: esun
#!/usr/bin/perl

open(FH, "file.txt");
my $flag = 0;

while (<FH>) {
. $flag = 1 if (/^Alpha$/);
. $flag = 0 if (/^$/);
. print if ($flag);
}

Remove the periods, they're just for indenting for the forum. This assumes you have a blank line between each set of data.

I'd tweak that flag = 0 statement to be /^\s*$/ unless you're really sure that line is only a carriage return.
 
Back
Top