in reply to Re^2: Conditional initialization of my-variables
in thread Conditional initialization of my-variables

> or to add a default value

> $input = 1 unless $input;

Careful! Many things are false in Perl, like 0 or ""

You probably meant

$input = 1 unless defined $input;

Anyway, both are IMHO better written as

$input ||= 1; # default if false # or $input //= 1; # default if undefined

Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^4: Conditional initialization of my-variables
by Bod (Parson) on Apr 08, 2023 at 17:55 UTC
    Careful! Many things are false in Perl, like 0 or ""

    Oh yes - care is needed. But very often that's exactly what I want.

    A common use case is query strings from HTML forms with checkboxes. The query string will have the key with no value. So if that's decoded into a Perl hash, the hash will be defined and the key exists but I want it to return false as it is an empty string.

      When dealing with empty strings, I'd rather check length

      Edit

      DB<13> p "false" unless "0" false DB<14> p "false" unless 0 false DB<15> p "false" unless length "0" DB<16> p "false" unless length undef false DB<17> use warnings; length undef DB<18> p "false" unless length "" false DB<19>

      Cheers Rolf
      (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
      Wikisyntax for the Monastery