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;