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

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.


Comment on Re: Extracting string from a file
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062231]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2014-12-29 14:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (188 votes), past polls