Home: Perl Programming Help: Beginner:
grep or filtering in perl

New User

Dec 5, 2012, 1:53 PM

Views: 2532
grep or filtering in perl


I am a beginner for perl usage.

I have a file that has multiple lines. For me the two lines of use are :
..... blah .... blah ....
The tool described : Hammer
..... blah .... blah ....
See Also : Wrench screw pliers nail
..... blah .... blah ....

I want to assign a variable to 4th variable (Hammer) based of the search string "the tool described"
an array for the See Also list (Wrench, screw, pliers, nail) based on the search string see also

I was trying to do such scripting with shell first, but want to move to perl because of its pros.

Thanks is advance.
Attachments: sample_file.txt (1.03 KB)


Dec 5, 2012, 7:38 PM

Views: 2524
Re: [anujoamon] grep or filtering in perl

Use regular expressions to find and parse each line of interest.

use strict; 
use warnings;
open my $IN, '<', 'sample_file.txt' or die "Cannot open sample_file.txt:$!";
my $variable;
my @array;
while (<$IN>) {
if (/The tool described : (\w+)/) {
$variable = $1;
if (/See Also : (.+)/) {
@array = split /\s+/, $1;
close $IN;
print "Tool described: $variable\n";
print "See Also: @array", "\n";

Good Luck,

New User

Dec 6, 2012, 8:54 AM

Views: 2518
Re: [BillKSmith] grep or filtering in perl

Thanks a lot Bill, it worked exactly as i wanted :)