in reply to Test Number of Elements In Array
Adding my 2 cents here ...
A trick I like for comparisons against a constant (for both arrays and scalars), is to put the constant on the left side of the == operator.
This has the nice effect of making it illegal to accidentally drop one of the '=' signs.
For example, in:
use strict; use warnings; my @array = ( 1, 2, 3 ); print "@array\n"; # Time passes... if (@array = 10) { # A typo -- should have been "(@array == 10)" print "@array\n"; # Causes an assignment, and a TRUE evaluation +! } else { print "The array doesn't have 10 values\n"; } # Prints: # 1 2 3 # 10 @array = ( 1, 2, 3 ); print "@array\n"; # Time passes... if (10 == @array) { # Can't accidentally do "(10 = @array)" print "@array\n"; # without getting a fatal error. } else { print "The array doesn't have 10 values\n"; } # Prints: # 1 2 3 # The array doesn't have 10 values
If you were to accidentally change "==" to "=" in "if (10 == @array" (or someone in the future did the same), the resulting error would reveal it:
Can't modify constant item in scalar assignment at x.pl line 26, near "@array) " Execution of x.pl aborted due to compilation errors.
I use it all the time now by habit, and I never have to worry about accidentally assigning instead of comparing. Of course, ymmv...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Test Number of Elements In Array
by JavaFan (Canon) on Jun 07, 2009 at 12:44 UTC | |
by liverpole (Monsignor) on Jun 07, 2009 at 15:45 UTC | |
by akho (Hermit) on Jun 07, 2009 at 15:58 UTC |