tags:

views:

144

answers:

2
$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 :)

+5  A: 

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.

Sorpigal
@Sorpigal, so the code suddenly has to get complicated :( But, thanks, thanks, thanks alot, "the contents of $1 and $2 are changed to be empty", this is the crux of the problem :) I've been stumped there for quite a while. Now I see what I was doing wrong. Thanks!
Mike
+1  A: 

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+)/;
FM
@FM, the code is a simplified version of a toy program I coded that has about 300 lines. I had got a workaround for the problem I mentioned. Well I've just checked the code, no, I didn't enable the warning, ah, that's another problem. Thanks for the illustration code. I'm feeling like I'm enlightened :)
Mike
You should always use strict; and use warnings; even in 'toy' code. When you fix all errors and warnings your code will be better.
Sorpigal
@Mike: this is not the first time you've been counselled to always use strict and warnings. Please start heeding this advice; you will be much happier and more productive :)
Ether
@Sorpigal and @Ether, I'll be heeding your advice for future codings. Thanks :)
Mike