in reply to Converting to number doesn't always work...
Consideration of the way Perl converts a string to a number is interesting, but I was puzzled by why all the other things that are done to $N in TEST() seem to have no effect. Here's the narrative I've imagined for the critical part of what's happening:
I guess an opcode decompilation could confirm my conjecture, but I'm too lazy to do this right now.c:\@Work\Perl\monks>perl use strict; use warnings; sub TEST { defined $_[0] or return 0; my $N = shift; printf "TEST('$N') called - "; local $SIG{__WARN__} = sub { # doing anything or nothing to $N has no effect here # return; # try this printf "(in warn '$N' -> "; $N =~ tr|0-9||cd; $N = "0$N"; $N = 'garbage'; printf "'$N') - "; }; printf "\$N is '$N' before += - "; $N += 0; printf "\$N is '$N' after += \n"; return int($N); } for my $n (qw(55 55x x55)) { my $m = TEST($n); print "TEST('$n') returns $m \n\n"; } __END__ TEST('55') called - $N is '55' before += - $N is '55' after += TEST('55') returns 55 TEST('55x') called - $N is '55x' before += - (in warn '55x' -> 'garbag +e') - $N is '55' after += TEST('55x') returns 55 TEST('x55') called - $N is 'x55' before += - (in warn 'x55' -> 'garbag +e') - $N is '0' after += TEST('x55') returns 0
Update: Re-writing the $N += 0; statement as $N = $N + 0; may allow better visualization of what I think happens: The $N + 0 expression must be evaluated first, and it's in this evaluation that the warning is triggered and a bunch of irrelevant things are done to $N; then the $N = ...; assignment is done, overwriting any changes to $N made by the $SIG{__WARN__} handler.
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Converting to number doesn't always work...
by harangzsolt33 (Deacon) on Nov 22, 2019 at 22:26 UTC | |
by AnomalousMonk (Archbishop) on Nov 23, 2019 at 09:24 UTC | |
by haukex (Archbishop) on Nov 23, 2019 at 16:42 UTC | |
by Don Coyote (Hermit) on Nov 25, 2019 at 18:51 UTC | |
by harangzsolt33 (Deacon) on Nov 23, 2019 at 14:18 UTC |