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

Hi
I hope that you can help me. I have a problem that is probably simple but I am going the long way about solving it. Here is the problem:
I have an array of elements of the following format:
blah::status integer:22 blah::max integer:5 ...
I want the value after 'blah::' to be set as a variable to the number. e.g status=22; max=5.

I am doing this a very awkward way at the moment. Here is what I am doing:
I am defining the variables e.g my (status, max, ...)
Then I am using a for loop with if and elsif statements for every element in the array to assign the values
if ($array[$i] =~ /.*status.*/) { $status = $array1[$i]; $status =~ s/^.*://; } if ($array[$i] =~ /.*max.*/) { $max = $array1[$i]; $max =~ s/^.*://; } ...etc
This seems very long winded since the arrays can get very big and this method means that I need an if statement for every element. Can you suggest a better way?
Thanks in advance

Replies are listed 'Best First'.
Re: Array problem
by Roy Johnson (Monsignor) on Jun 16, 2004 at 21:41 UTC
    Use a hash with, e.g., status as a key:
    if ($array[$i] =~ /(status|max)/) { $hash{$1} = $array1[$i]; $hash{$1} =~ s/^.*://; }

    We're not really tightening our belts, it just feels that way because we're getting fatter.
      Thanks Roy
      That worked brilliantly
Re: Array problem
by jeffa (Bishop) on Jun 16, 2004 at 21:41 UTC

    Not exactly sure what you want the results to look like, next time, please post that as well. How about something like this:

    while (<DATA>) { my ($name,$type,$value) = $_ =~ /^blah::(\w+)\s+(\w+):(\d+)/; print "blah::$name=$value\n" if $name and $value; } __DATA__ blah::status integer:22 blah::max integer:5
    Which prints out:
    blah::status=22
    blah::max=5
    
    Is this what you wanted?

    UPDATE: no, it isn't. Just do what Roy Johnson suggested or try:

    my %table; while (<DATA>) { my ($name,$type,$value) = $_ =~ /^blah::(\w+)\s+(\w+):(\d+)/; $table{$name} = $value if $name and $value; }
    I prefer to pick out the parts in case i need them later, instead of substituting out what i don't need.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Array problem
by borisz (Canon) on Jun 16, 2004 at 21:49 UTC
    This peace of code collects everything after :: as the key name and put anything after the : as the value into the hash %answers.
    my %answers ; for ( @array ) { /::([\S]+)[^:]*:(.*)/ and $answers{$1} = $2 ; }
    Boris