in reply to fun(?) with +=

Your problem is with the line

my $foo = shift || 1;

Consider what happens if you give this program a command line argument of 0.

"shift" returns the value of the first command line argument - which is 0, therefore "shift || 1" will be 1.

You need to think about the difference between the truth value of a variable and it's defined value. You want to check that your command line argument is defined - not that it is true.

You probably want something like this:

$foo = shift; $foo = 1 unless defined $foo;

In Perl 5.10 you'll be able to use the "defined or" test to make this code easier.

$foo = shift // 1;
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: fun(?) with +=
by Anonymous Monk on Jan 03, 2005 at 12:26 UTC
    I'd write that as:
    $foo = @ARGV ? 1 : shift;
    which, IMO, gives a clearer message that '1' the default if no arguments are given.
      Do you mean that you'd write it as:

      $foo = @ARGV ? shift : 1;

      (I think you may have the 1 and shift switched.)