I have a sub called TEST() which converts every sort of input to a number. It should return 0 if the input value is undefined or uninitialized or blank or contains letters only. But if it contains digits, it should return those digits only.
So, if I ask to convert "55a" then it returns "55" which is fine. But if I try to convert "a55" then it returns 0, which baffles me! It should return 55. Why does this happen?
Edit: It seems like I am able to access the value of $N from within the warning exception, but I cannot modify it. The changes do not stick. So, I guess the question is how can I export the value of $N from within the warning sub { } so that it would overwrite the value of $N in the TEST sub?
#!/usr/bin/perl -w use strict; use warnings; my @TEST_VALUES = ('55a', 'a55'); foreach my $i (@TEST_VALUES) { print "Calling TEST('$i'): "; print "\nTEST return value = ", TEST($i), "\n"; } exit; ####################################### sub TEST { print " TEST() was called "; defined $_[0] or return 0; my $N = shift; print "with argument: '$N'\n"; # If we get a warning, it's probably because $N # is not a number. So, we remove all non-digits # and then it becomes a number! local $SIG{__WARN__} = sub { print "\t\t(((warning '$N'->"; $N =~ tr +|0-9||cd; $N = "0$N"; print "'$N')))\n"; }; $N += 0; print "\nThe value of N is now '$N'\n"; return int($N); }
In reply to Converting to number doesn't always work... by harangzsolt33
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |