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

N00bie Alert

I was trying to do what I thought was a simple conditional assignment using the  ?: operator on a hash value. The code follows

%HashTemplate =( several key value pairs );
%WorkingCopy = ();
$key = 0;
%WorkingCopy = %HashTemplate;
 for $key (keys $WorkingCopy) {
  $WorkingCopy{$Key} = /p1/ ? "this" : "that";
 }

what I expected was that whenever $WorkingCopy{$key}= /p1/was true (i.e., matched the value), "this" would be assigned to $WorkingCopy{$key}; if false (match failed) "that" would be assigned to $WorkingCopy{$key}

I even tried the alternative:
$WorkingCopy{$Key} = /p1/ ? $WorkingCopy{$key} = "this" : $WorkingCopy{$key} = "that";

In all cases the match fails as written, resulting in: ($WorkingCopy{$key} = "that" for all elements in the hash. Even with different permutations of p1 --e.g, quoted or not quoted within forward slashes, the match fails. (I know p1 exists as hash value).

I've read through the pertinent parts of Camel several times (followed their example), but I'm obviously still missing something basic in my understanding of ?: in a pattern matching expression as above. any light you can shed on my (mis)understanding of the ?: and my example, is most appreciated.

thanks in advance

Replies are listed 'Best First'.
Re: ?: conditionals
by almut (Canon) on Jan 18, 2010 at 00:49 UTC
    ...that whenever $WorkingCopy{$key}= /p1/ was true (i.e., matched the value), "this" would be assigned to $WorkingCopy{$key}; if false (match failed) "that" would be assigned to $WorkingCopy{$key}

    Perhaps you meant

    $WorkingCopy{$key} = $WorkingCopy{$key} =~ /p1/ ? "this" : "that";

    (as you have it, /p1/ is being matched against $_)

      Yes, that works perfectly. many thanks
Re: ?: conditionals
by SpiceMan (Sexton) on Jan 18, 2010 at 08:41 UTC
    Always, always...
    use strict; use warnings;
    That code won't even run since the code have several errors. By keys $WorkingCopy you meant keys %WorkingCopy, and you're trying to use $WorkingCopy{$Key} when the loop assigns the key to $key, etc...