in reply to fun(?) with +=

Be careful with "trial and error programming" (also called "programming by accident"). It is always better to understand what you are doing. In this particular case, the problems are in operator precedence and in "what is truth?", both covered in detail in any Perl book or in perldoc.

Replies are listed 'Best First'.
fixed the problem
by Anonymous Monk on Jan 03, 2005 at 06:14 UTC
    After studying up a bit on defined, finally figured out what to do. Here is the code

    #!/usr/bin/perl use strict; use warnings; my $baz = 0; my $foo = shift; $foo = 1 if !defined($foo); chomp(my @bar = qw( etc etcetera )); die if $foo < 1; while($baz < $foo){ $baz += 1; print "$bar[rand @bar] ", "ad infinitum\n"; }

    It returns a single result if nothing is entered at command line, and it returns error message if you select 0 or less at the command line. It works properly in every other respect as well.

    Thanks, Perlmonks!
      Update: This is redundant; davorg already said it above!

      Since what you wanted to do is a common need, future versions of perl are supposed to include a "defined-or" operator:

      $x //= 1; # same as $x = $x // 1;

      will be equivalent to

      $x = defined $x ? $x : 1; # same as $x = 1 unless defined $x