Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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; }
    HTH.

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2020-07-14 09:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?