Mike
Mike

Reputation: 1851

Why this code does not do what I mean?

$w = 'self-powering';
%h = (self => 'self',
      power => 'pauә',
      );
if ($w =~ /(\w+)-(\w+)ing$/ && $1~~%h && $2~~%h && $h{$2}=~/ә$/) {
    $p = $h{$1}.$h{$2}.'riŋ';
      print "$w:"," [","$p","] "; 
}

I expect the output to be

self-powering: selfpauәriŋ

But what I get is:

self-powering: [riŋ]

My guess is something's wrong with the code

$h{$2}=~/ә$/

It seems that when I use

$h{$2}!~/ә$/

Perl will do what I mean but why I can't get "self-powering: selfpauәriŋ"? What am I doing wrong? Any ideas?

Thanks as always for any comments/suggestions/pointers :)

Upvotes: 1

Views: 206

Answers (2)

FMc
FMc

Reputation: 42411

Are you running with use warnings enabled? That would tell you that $1 and $2 are not what you expect. Your second regex, not the first, determines the values of those variables once you enter the if block. To illustrate with a simpler example:

print $1, "\n"
    if  'foo' =~ /(\w+)/
    and 'bar' =~ /(\w+)/;

Upvotes: 1

sorpigal
sorpigal

Reputation: 26086

When you run

 $h{$2}!~/ә$/

In your if statement the contents of $1 and $2 are changed to be empty, because no groupings were matched (there were none). If you do it like this:

if ($w =~ /(\w+)-(\w+)ing$/){
    my $m1 = $1;
    my $m2 = $2;
    if($m2~~%h && $m2~~%h && $h{$m2}=~/ә$/) {
        $p = $h{$m1}.$h{$m2}.'riŋ';
        print "$w:"," [","$p","] "; 
    }
}

I expect you will get what you want.

Upvotes: 6

Related Questions