moensch has asked for the wisdom of the Perl Monks concerning the following question:
The function is supposed to return the sum of the decimal ASCII value of each character in the given string $in. Call it the first time (let's say, with the string foo), it returns 324, call it again, it returns 0. I then thought, that maybe the code in ?{} is not executed at all, but try replacing the regex with this:sub getChecksum($) { my $in = shift; my $check = 0; $in =~ m/(?:(.)(?{$check += ord($1);}))*^/; return $check; }
You'll see that even on the second call, it evaluates the code in ?{}, but does not increment $check.$in =~ m/(?:(.)(?{print "ASCII value of '$1' is: ".ord($1)."\n"; $chec +k += ord($1);}))*^/;
Surely I could replace the regex with this:getChecksum called with: 'foo' ASCII value of 'f' is: 102 ASCII value of 'o' is: 111 ASCII value of 'o' is: 111 will return '324' getChecksum called with: 'foo' ASCII value of 'f' is: 102 ASCII value of 'o' is: 111 ASCII value of 'o' is: 111 will return '0'
But who would want this when it should(?) work in the regex? ;-) I am running this on debian etch (perl v5.8.8). Anybody who has an explanation for this is allowed to run to the shop and buy himself a cookie :Dmy @chars = split( //, $in ); foreach my $char (@chars) { $check += ord($char); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Weird behaviour with match-time code evaluation and backtracking
by Corion (Patriarch) on Mar 05, 2008 at 08:16 UTC | |
|
Re: Weird behaviour with match-time code evaluation and backtracking
by BrowserUk (Patriarch) on Mar 05, 2008 at 09:16 UTC | |
by ikegami (Patriarch) on Mar 05, 2008 at 09:42 UTC | |
|
Re: Weird behaviour with match-time code evaluation and backtracking
by ikegami (Patriarch) on Mar 05, 2008 at 09:39 UTC | |
|
Re: Weird behaviour with match-time code evaluation and backtracking
by stiller (Friar) on Mar 05, 2008 at 09:04 UTC |