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

I am trying to extract the number from a string such as : keff = 1.23456 with an estimated standard deviation of 0.12345. I am interested in extracting both numbers, which will change with the data file. I tried to do this with a test program first to see how it works:
$out_file = out1; open (OUT. "$out_file"); while (OUT) { if (/Time: (..):(..):(..)/) { $hours = $1; $mins = $2; $secs = $3; } } close (OUT); print "hours =: $hours";
The out file contains a single line: Time: 04:18:02 I get an error message stating: Use of unintialized value in pattern match (m//) at test.pl line 8. What am I doing wrong? If I can get this case to work, maybe I can get the first and more complicated case working. Thanks, Bruce

Replies are listed 'Best First'.
Re: extracting number from middle of string
by Ovid (Cardinal) on Apr 12, 2002 at 20:44 UTC

    You need to add an or die to the file open to ensure that it opened correctly. You also need to add angle brackets around the filehandle to read it. There also needs to be a comma after the filehandle in the open (and not a period).

    $out_file = out1; open (OUT, "< $out_file") or die "Cannot open $out_file for reading: $ +!"; while (<OUT>) { if (/Time: (..):(..):(..)/) { $hours = $1; $mins = $2; $secs = $3; } } close (OUT); print "hours =: $hours";

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: extracting number from middle of string
by joealba (Hermit) on Apr 12, 2002 at 20:41 UTC
    If you have warnings turned on, you'll get that error if $_ is empty. Try:
    $out_file = "out1"; open (OUT, "$out_file"); while (<OUT>) { next unless $_; if (/Time: (..):(..):(..)/) { $hours = $1; $mins = $2; $secs = $3; } } close (OUT); print "hours =: $hours";
    Now, this *is* just test code, right? Note that you're checking every line for this match, but then you print after your while loop completes. You may want to bail once you've hit the match.

    For testing simple things like this early in development, I often use those whacky in-code filehandles: __DATA__. So, I'd do something like this:
    while (<DATA>) { if ($_ && /Time:\s+(\d+):(\d+):(\d+)/i) { $hours = $1; $mins = $2; $secs = $3; last; } } print "hours =: $hours"; __DATA__ Time: 04:45:12
    Give it a shot. It's cool! All the kids are doing it...
Re: extracting number from middle of string
by ehdonhon (Curate) on Apr 12, 2002 at 20:52 UTC

    Other monks have already pointed out the problems with the way you are reading from the OUT handle. For more info on regular expressions, you could try doing a search for "extracting". I found a number of nodes.

    Extracting a substring?
    extracting numbers from a string

    And there are many others