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

Hi there;
I have a variable:
$results = "Home Town, Log in activity: 57 DI activity: 13 FA activity +: 13 FAI activity: 4 Login activity: 23 Not Found activity: 4"; #The values here are after parsing been done. $1 = 57; $2 = 13; $3 = 13; $4 = 4; $5 = 23; $6 = 4;

I am trying to extract the individual numbers to a different variable, and don't know if I should use regular expressions or use split any help?
Thank you!!!!

Replies are listed 'Best First'.
Re: Parsing String
by davido (Cardinal) on Apr 21, 2004 at 18:40 UTC
    Split is an interesting idea. ...this ought to do it:

    my $results = "Home Town, Log in activity: 57 DI activity: 13 FA activ +ity: 13 FAI activity: 4 Login activity: 23 Not Found activity: 4"; my @numbers = split /\D+/, $results; print "$_\n" for @numbers;

    If you want to do it with an RE instead, just use the /g modifier in list context like this:

    my $results = "Home Town, Log in activity: 57 DI activity: 13 FA activ +ity: 13 FAI activity: 4 Login activity: 23 Not Found activity: 4"; my @numbers = $results =~ m/\d+/g; print "$_\n" for @numbers;


    Dave

      my @numbers = split /\D+/, $results;

      The problem with this is that it creates an extra empty element at the beginning of the @numbers array. Go for the RE solution.

      just another dave

      Dave, thank you for pointing out the /g modifier! I had complete forgotten about that fact when I posted my answer.

        I couldn't get it to work I am trying to go item by item using reg. expressions.
•Re: Parsing String
by merlyn (Sage) on Apr 21, 2004 at 20:14 UTC
    $results = "Home Town, Log in activity: 57 DI activity: 13 FA activity +: 13 FAI activity: 4 Login activity: 23 Not Found activity: 4"; #The values here are after parsing been done. $1 = 57; $2 = 13; $3 = 13; $4 = 4; $5 = 23; $6 = 4;
    OK, I'm gonna call HOMEWORK on this one. If you don't know whether to use a split or a regex, why would you specify the problem as "$1 contains 57".

    Maybe it's just my years as a Perl instructor, or just someone who works with beginners a lot. This just sounds like a very artificial setup for a problem.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Parsing String
by Belgarion (Chaplain) on Apr 21, 2004 at 18:39 UTC

    A regex might be the easiest at this point:

    $results = "Home Town, Log in activity: 57 DI activity: 13 FA activity +: 13 FAI activity: 4 Login activity: 23 Not Found activity: 4"; my @values; $results =~ s/[^:]*: (\d+)/push @values, $1/eg; print $_, "\n" foreach @values; __OUTPUT__ 57 13 13 4 23 4
    This will push each number into the @values array.

Re: Parsing String
by Zaxo (Archbishop) on Apr 22, 2004 at 00:56 UTC

    To get matches in $1 through $6 you'll need six sets of parentheses in a single regex.

    After Compline,
    Zaxo