clsyee has asked for the wisdom of the Perl Monks concerning the following question:

I'm a newbie. I have a long list of data where i need to extract speficic word from a specific line. The line i'm interested is "All avg = 12 Total avg = 3". From this line, i only want to extract out "All avg = 12". I need help to modify the condition.

Below is my sample code:

#!/usr/local/bin/perl5 # # Program to transpose temp1.txt # $dirname = "C:\\cynthia\\perl"; print "\n\nDirectory is : $dirname\n\n"; opendir (DATADIR, $dirname) or die "can't opendirname; $!"; $filename = "temp.pl"; print "Filename is : $filename\n\n"; open(LINE,"temp2.txt")|| die "\nERROR: Could not open input file $infi +lename"; # assign the first line to a variable # $line = <LINE>; # use a loop to keep reading the file # until it reaches the end while ($line = <LINE>) { chomp $line; if ($line =~m/^All avg/ ){ print "$line\t"; }else{ print "$line\n\n"; } } # close file when done close(LINE); #close dir closedir (DATADIR); # display message when done print "DONE!\n";

Code tags and formatting added by GrandFather

Replies are listed 'Best First'.
Re: Extract specific word from a phrase
by McDarren (Abbot) on Aug 10, 2006 at 05:42 UTC
    hmm, there are all sorts of problems with your code as is.

    Firstly, you're not using strict or warnings. That's bad™

    Secondly, you do an opendir, but then you do nothing with the directory handle. That's a bit pointless.

    Next, in your open line, you refer to $infilename - which has not been previously defined (strict and warnings would have alerted you to this).

    So... here is a canonical way to achieve what you seem to be asking (untested):

    #!/usr/bin/perl use strict; use warnings; my $file = '/path/to/file.txt'; open IN, "<", $file or die "Could not open $file:$!\n"; my $wanted; while (my $line = <IN>) { if ($line =~ /(All avg = \d+)/) { $wanted = $1; last; # get rid of this if you need/expect to match multiple + lines } }

    That should be enough to get you going.

    Update: added the "last" to the code, as per suggestion from ikegami

    Cheers,
    Darren :)

Re: Extract specific word from a phrase
by rodion (Chaplain) on Aug 10, 2006 at 10:39 UTC
    There's one other thing in the code that might trip you up if it's still there. Just before the "open()", you're setting "$filename" to "temp.pl", but opening "temp2.txt", and reporting an error on "$infilename", which is not defined.

    Even experienced programmers can read a line with these types of errors and see what they meant to write, rather than see the error, so it's a good thing to fix, even if it's not what's giving you problems right now. ("use strict" will help you with the two different variable names, but not with opening "temp2.txt" instead of using the name in the variable.)

    Good luck, and keep plugging away.