Hi monks
I have managed to create a function which returns a different result the second time you call it - with the same parameter. To cut things short, here it is:
sub getChecksum($) {
my $in = shift;
my $check = 0;
$in =~ m/(?:(.)(?{$check += ord($1);}))*^/;
return $check;
}
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:
$in =~ m/(?:(.)(?{print "ASCII value of '$1' is: ".ord($1)."\n"; $chec
+k += ord($1);}))*^/;
You'll see that even on the second call, it evaluates the code in ?{}, but does not increment $check.
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'
Surely I could replace the regex with this:
my @chars = split( //, $in );
foreach my $char (@chars) {
$check += ord($char);
}
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 :D
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.