Simple Perl Question

BChico

Platinum Member
May 27, 2000
2,742
0
71
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?
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
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.
 

jman19

Lifer
Nov 3, 2000
11,225
664
126
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.
 

esun

Platinum Member
Nov 12, 2001
2,214
0
0
#!/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.
 

esun

Platinum Member
Nov 12, 2001
2,214
0
0
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.
 

Daverino

Platinum Member
Mar 15, 2007
2,004
1
0
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.