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

I'm looking for a better/more elegant way to achieve the following, without a %temp variable. Any takers ?
use strict; use Data::Dumper; my $Incoming = 'uno="one" Blah blah dos="two" * More Noise* tres="thr +ee"'; my %att= (PREEXISTING=>"val1", ANOTHER=>"Val2"); my %temp = $Incoming=~m/\W*(\w+)="([^"]+)"/ig; $att{uc $_}=$temp{$_} for keys %temp; print Dumper \%att; #--- Output -- #$VAR1 = { # 'TRES' => 'three', # 'UNO' => 'one', # 'DOS' => 'two', # 'ANOTHER' => 'Val2', # 'PREEXISTING' => 'val1' # };
(I have no control over the content of $Incoming).
I would want to do this in STANDARD perl - no modules, compatible with perl 5.10.

     Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

Replies are listed 'Best First'.
Re: Pair-wise list access - without temp hash
by wind (Priest) on Feb 25, 2011 at 05:16 UTC
    Could just use a while loop instead, but it's not that much different:
    use strict; use Data::Dumper; my %att = (PREEXISTING => "val1", ANOTHER => "Val2"); my $Incoming = q{uno="one" Blah blah dos="two" * More Noise* tres="th +ree"}; while ($Incoming =~ m/\W*(\w+)="(.*?)"/g) { $att{uc $1} = $2; } print Dumper \%att;
      Very nice(++), Thanks.!
      (I need the "i" for a different reason in the "real" code. Your code inspires:
      $att{uc $1} = $2 while $Incoming =~ m/\W*(\w+)="([^"]+)"/gi;
      Which feels close to 'right'.
      (I feel more comfortable with the explicit "not quote", as opposed to the non-greedy dot-star).

           Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

        Sounds like you want

        for_pairs { $att{$a} = $b } /\W*(\w+)="([^"]+)"/ig;

        Let us know if you need help writing for_pairs.

Re: Pair-wise list access - without temp hash
by BrowserUk (Patriarch) on Feb 25, 2011 at 05:21 UTC

    This avoids the temporary, but I'm not sure that it is any better for doing so:

    use strict; use Data::Dumper; my $Incoming = 'uno="one" Blah blah dos="two" * More Noise* tres="thr +ee"'; my %att= (PREEXISTING=>"val1", ANOTHER=>"Val2"); $att{ uc $_->[ 0 ] } = $_->[ 1 ] for map[ m[(\w+)="([^"]+)"] ], $Incoming =~ m[\W*(\w+="[^"]+")]ig; print Dumper \%att;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.