mabman2 has asked for the wisdom of the Perl Monks concerning the following question:

This is probably something really simple, but I don't understand why the code below doesn't work properly - ex, the IF statement in the subroutine doesn't evaluate properly. In the example below, @_ is always correct as printed, but it always hits the first IF statement, even if @_ is "2.0000".

I have also tried changing the comparison operator to "eq" tried the match "=~", but it still won't work correctly.

Thanks in advance.

#!usr/bin/perl sub test { print "@_\n"; if (@_ == 1.0000) { print "entering loop 1\n"; $hashname = "hash1"; } elsif (@_ == 2.0000) { print "entering loop 2\n"; $hashname = "hash2"; } print "$hashname\n"; return ($hashname); } %hash1 = ( 1 => 1.1, 2 => 2.2, 3 => 3.3, ); %hash2 = ( 1 => 4.4, 2 => 5.5, 3 => 6.6, ); $hash = test(sprintf("%.4f", 2)); print $$hash{1}; exit;

Replies are listed 'Best First'.
Re: IF statements not being evaluated as expected
by ikegami (Patriarch) on Dec 13, 2009 at 04:36 UTC

    You're testing if the array is equal to 1 when you should be testing the first element of the array.

    What does it mean for an array to be equal to one? It means it contains one element. An array returns the number of elements it containes when evaluated in scalar context.

    You could use $_[0] directly, but it's traditional to name your arguments. Fixed:

    sub test { my ($arg) = @_; print "$arg\n"; if ($arg == 1) { print "entering loop 1\n"; $hashname = "hash1"; } elsif ($arg == 2) { print "entering loop 2\n"; $hashname = "hash2"; } print "$hashname\n"; return ($hashname); }

    Simplified:

    sub test { my ($arg) = @_; if ($arg == 1) { return 'hash1'; } elsif ($arg == 2) { return 'hash2'; } die; }