I have a situation where I expect variables to be passed to me as strings or numbers.
i.e.
sub foo {
# These can be either strings or numbers
my ($bar, $var, $star) = @_;
# I need to check to see if $bar is the number 0 (zero)
if ($bar == 0) {
# Do super magic with it
}
}
Unfortunately Perl tries to do the super magic on $bar when it contains a string.
How can I tell Perl to do super magic on $bar if and only if it is the number 0 (zero)?
I understand Perl fundamentally interprets based on context, which is the underlying problem here. A possible solution to this problem is to use regex, which is fine, but I wanted to know if there was another more “straight-forward” solution.
Thanks in advance.
I’d personally go with what @Disco3’s comment said.
This works for
$bar = 0,$bar = 'foo'and$bar = 123giving the expected result.Here’s a fun fact, though:
Benchmarking these three solutions tells us that the unquoted
0is the fastest way to do it.