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

Greetings,

I have a string formatted closely to the following example:

examplestringofrandomlength/userid=6&refid=49

I am trying to extract the two numbers and insert them into their own scalars so that:

$num1 = 6

$num2 = 49

Also note that the first number(6) will always be between 1-6 whereas the second number(49) ranges from 1-9999.

Replies are listed 'Best First'.
Re: Extracting two numbers from a string
by BrowserUk (Patriarch) on May 28, 2010 at 17:17 UTC

    $str = 'examplestringofrandomlength/userid=6&refid=49';; ( $num1, $num2 ) = $str =~ m[userid=(\d+)[;&]refid=(\d+)];; print for $num1, $num2;; 6 49
Re: Extracting two numbers from a string
by toolic (Bishop) on May 28, 2010 at 17:16 UTC
    use strict; use warnings; my $num1; my $num2; my $s = 'examplestringofrandomlength/userid=6&refid=49'; if ($s =~ / (\d+) \D+ (\d+) /x) { $num1 = $1; $num2 = $2; } print "num1=$num1\n"; print "num2=$num2\n"; __END__ num1=6 num2=49

    perlre

      Thank you so much. I apologize for being a newbie
Re: Extracting two numbers from a string
by kennethk (Abbot) on May 28, 2010 at 17:14 UTC
    What have you tried? What didn't work? See How do I post a question effectively?.

    A regular expression will likely do what you want:

    my $string = 'examplestringofrandomlength/userid=6&refid=49'; my ($num1, $num2) = $string =~ /\d+/g;

    See perlretut, in particular Using regular expressions in Perl.

    Note that given the simplicity of this expression, it can fail in many ways - for example, if your string is really stringwithnumber111/userid=6&refid=49, you'll get the wrong result. If this is an issue, post a more accurate and complete set of sample strings.

Re: Extracting two numbers from a string
by syphilis (Archbishop) on May 28, 2010 at 22:38 UTC
    use strict; my $str = 'examplestringofrandomlength/userid=6&refid=49'; my ($discard, $num1, $num2) = split /=/, $str; $num1 += 0; print "$num1\n$num2\n";
    Cheers,
    Rob
Re: Extracting two numbers from a string
by Anonymous Monk on May 28, 2010 at 21:34 UTC
    #!/usr/bin/perl -- use strict; use warnings; use CGI(); my $q = CGI->new('examplestringofrandomlength&userid=6&refid=49' ); for my $p( qw! userid refid ! ){ print "$p = ", scalar $q->param($p), "\n"; } __END__ userid = 6 refid = 49