in reply to What's happening to my $1?

I would agree with you that, this is a problem, as the behavior is not consistant.

However this can also be looked at from a different angle. Although it is not clearly stated, or only vaguely mentioned, it is unsafe to use $1 after a failed match, and it is up to you to execise your caution.

I consider this as some sort of grey area. It will be nice if the consistancy is there, but that kind of consistancy was not clearly promised.

By the way, in your first piece of code, there is no need to initialize the hash elements to 0. This is Perl ;-)

my %totals; while ( <DATA> ) { chomp; if ( /(^[a-z].*$)/i ) { #I deleted the initialization here, and you still get what you expe +cted } else { $totals{$1} += $_; } } print "$_: $totals{$_}\n" for keys %totals; __DATA__ player1 11 22 11 player2 10 21 player1 22

Replies are listed 'Best First'.
Re: Re: What's happening to my $1?
by Not_a_Number (Prior) on Jan 21, 2004 at 19:46 UTC
    By the way, in your first piece of code, there is no need to initialize the hash elements to 0. This is Perl ;-)

    Thanks, you're right, of course. However, I happen to hate empty if blocks.

    Don't worry, it's just a personal thing ;-). So I re-wrote my original code (which I'll probably never use again since it's proved so fragile):

    my %totals; while ( <DATA> ) { chomp; /(^[a-z].*$)/i or $totals{$1} += $_; }

    Thanks again for the tip.

    dave