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

Is there an idiomatic way of writing

$total += $increment if $increment

? Thanks!
--TWH

Replies are listed 'Best First'.
Re: Idiomatic Perl
by Limbic~Region (Chancellor) on Mar 02, 2004 at 18:15 UTC
    Anonymous Monk,
    This can be trickier than it first appears due to the fact that $increment may exist but not be numeric - pesky warnings and strictures. You also run into a problem if the $increment is not defined since looks_like_number says that an undefined value looks numeric.
    #!/usr/bin/perl use strict; use warnings; use Scalar::Util 1.10 'looks_like_number'; my $total = 4; my $increment = 'blah'; $total += $increment || 0 if looks_like_number( $increment );
    Cheers - L~R
      In the spirit of TIMTOWTDI and my well-beloved ternary abuse (which I like since many other languages have it):

      $total += looks_like_number($increment) ? $increment : 0
        flyingmoose,
        This won't work for the reason I described above. If $increment is undefined looks_like_number will still return true.
        #!/usr/bin/perl use strict; use warnings; use Scalar::Util 1.10 'looks_like_number'; my $total = 4; my $increment; $total += looks_like_number($increment) ? $increment : 0 __END__ Use of uninitialized value in addition (+) at blah.pl line 9.
        Cheers - L~R
Re: Idiomatic Perl
by Anonymous Monk on Mar 02, 2004 at 18:13 UTC
Re: Idiomatic Perl
by ysth (Canon) on Mar 02, 2004 at 23:18 UTC
    Why not just that way?

    You can shorten it to $total += $increment if you are sure increment is a number.

    $total += $increment || 0 will avoid warning if $increment is undefined, but your original version reads better (at least to my eyes).

Re: Idiomatic Perl
by arden (Curate) on Mar 02, 2004 at 18:11 UTC
    You don't need the if because if $increment isn't defined yet, its value will be 0, therefore   $total += $increment; will still equal   $total.

    - - arden.

    update: I agree with Limbic~Region, I was simply making the case for adding up numbers based on the existence or non-existence of a variable.

      arden,
      I disagree if you are trying to avoid Use of uninitialized value in addition (+) at.... You also will have a problem if it is defined but not numeric. See my solution below.

      Cheers - L~R