Conrad.Irwin has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I am trying to parse a string as shown below, I am currently using a series of regex to parse the string, but I feel that there must be a way to do this in one go. Can anyone nudge me in the right direction? Conrad
if( $param ){ if( $param =~ /id:(\S*)/){ $ENV{'C:id'}=$1; } if( $param =~ /key:(\S*)/){ $ENV{'C:key'}=$1; } if( $param =~ /limit:(\S*)/){ $ENV{'C:limit'}=$1; } ... }

Replies are listed 'Best First'.
Re: Regular Expressions Match Repititions
by Corion (Patriarch) on Jul 22, 2007 at 19:10 UTC

    You can extract both, the key and the value in one go. Maybe you want some sanity checking on the key or maybe not:

    if ($param) { $param =~ /^(id|key|limit):(\S*)$/ or die "Malformed value for par +ameter: '$param'"; my ($key,$value) = ($1,$2); $ENV{"C:$key"} = $value; };

    If you don't want the sanity check on the parameters, for easy extensibility, it gets even shorter:

    if ($param) { $param =~ /^(\w+):(\S*)$/ or die "Malformed value for parameter: ' +$param'"; my ($key,$value) = ($1,$2); $ENV{"C:$key"} = $value; };
Re: Regular Expressions Match Repititions
by b4swine (Pilgrim) on Jul 22, 2007 at 19:08 UTC
    How about
    $ENV{"C:$1"} = $2 while $param =~ /(id|key|limit):(\S*)/;
      Sorry I meant
      $ENV{"C:$1"} = $2 while $param =~ /(id|key|limit):(\S*)/g;
        Thank you very much for your help. I shouldn't have asked you to do my homework for me - but you have saved me a long time. I am now using  $ENV{"C:$1"} = $2 while $param =~ /(\w*):(\S*)/g;