Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Obtain information from a string

by Baz (Friar)
on Apr 29, 2002 at 22:06 UTC ( #162937=perlquestion: print w/replies, xml ) Need Help??

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

Lets say I had a large string (stored in a variable) and in that string somewhere was the string "Total Cost: X", where X represents a arbitrary number. How could I store this value X in a variable of its own? And lets also say that if the above string is missing the stored value should be zero.

Replies are listed 'Best First'.
Re: Obtain information from a string
by stephen (Priest) on Apr 29, 2002 at 22:17 UTC
Re: Obtain information from a string
by VSarkiss (Monsignor) on Apr 29, 2002 at 22:15 UTC

    TIMTOWTDI, but this is probably the simplest:

    if ($largestring =~ /Total Cost: (\d+)/) { $x = $1; } else { $x = 0; }

Re: Obtain information from a string
by thelenm (Vicar) on Apr 29, 2002 at 22:23 UTC
    Use a regular expression. If you don't understand why this works, see perlre. Is "X" a dollar amount, an integer, or some other number format? This will work for integers:
    my $string = "foo bar baz blah Total Cost: 480 foo foo foo"; my ($cost) = $string =~ /Total\s+Cost:\s*(\d+)/; $cost ||= 0;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://162937]
Approved by VSarkiss
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2020-08-10 08:09 GMT
Find Nodes?
    Voting Booth?
    Which rocket would you take to Mars?

    Results (56 votes). Check out past polls.