Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^3: Conditional initialization of my-variables

by LanX (Saint)
on Apr 07, 2023 at 19:40 UTC ( [id://11151512]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11151512]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2026-05-12 06:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.