Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Extracting string from a file

by sundialsvc4 (Abbot)
on Nov 12, 2013 at 16:23 UTC ( #1062231=note: print w/replies, xml ) Need Help??

in reply to Extracting string from a file

There is, of course, “more than one way to do it,™” but I think that the way that I would do it is to use the /g modifier as discussed in perldoc perlretut.

Something like ... (caution... extemporaneous code; your syntax may vary)

while (my $line = <FH>) { next unless $line =~ /^\~\|TOTAL/; my @percents = ( $line =~ /([\d\.]+)/g ); .. do something with @percents .. }

First, we ignore any lines outright which do not begin with the proper string ... notice the use of the "^" symbol to anchor to start-of-line, and the backslash-escaping of special symbols that otherwise would be taken as part of (ill-formed) regular expression syntax.

Then, “the interesting bits” in the string are groupings of digits-and-decimal-points, so we gather up as many of them as are present anywhere in the line.   In so-called “array context,” Perl will return an array containing all of the values found, without using a loop to do so, although we certainly could have done so using so-called “scalar context.”   Notice the use of parentheses to indicate a substring that we wish to extract.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062231]
[karlgoethebier]: i guess i've been ikegamid, he

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (10)
As of 2017-11-23 17:10 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (336 votes). Check out past polls.