Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: if defined not working

by 1nickt (Canon)
on Feb 04, 2016 at 16:39 UTC ( [id://1154408]=note: print w/replies, xml ) Need Help??


in reply to Re: if defined not working
in thread if defined not working

Hi Athanasius,

I'm curious, what in your view is the advantage of using Logical Defined-Or over simple Logical Or in the OP's situation?

$ perl -Mstrict -Mwarnings -E' my $foo; say (defined $foo ? "1: defined" : "1: not defined"); my $bar = $foo; say "2: bar: $bar"; my $baz = $foo || "baz"; say "3: baz: $baz"; my $qux = $foo // "qux"; say "4: qux: $qux"; ' 1: not defined Use of uninitialized value $bar in concatenation (.) or string at -e l +ine 5. 2: bar: 3: baz: baz 4: qux: qux

Thanks!

The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^3: if defined not working
by stevieb (Canon) on Feb 04, 2016 at 17:01 UTC

    Hey Nick,

    The difference really only matters if what you're checking has a false value (that you may not know about, such as when looping through a hash). A false value is still defined:

    perl -wMstrict -E 'my $x=0; say $x||1; say $x//2;' 1 0

    Update: here's a tiny example that shows that in a larger application, not checking for defined can be an issue when you aren't explicitly looking for truth:

    use warnings; use strict; this(arg => 0); sub this { my %args = @_; do_something("if\n") if $args{arg}; do_something("if def\n") if defined $args{arg}; } sub do_something{ print shift; }
Re^3: if defined not working
by mr_mischief (Monsignor) on Feb 04, 2016 at 17:38 UTC
    my $one = 1; my $zero = 0; my $undef; my $result; $result = 1; # 1 $result = 1 || 0; # also 1 $result = 0 || 1; # also 1 $result = $zero || $one; # also 1 $result = $zero // $one; # 0 $result = $zero // 1; # 0 as well $result = 0 // 1; # 0 as well $result = $undef // $one; # 1 again $result = $undef || $one; # 1 again $result = fork || die; # dies in the child process or if failing to + fork $result = fork && die; # dies in the parent process $result = fork // die; # dies in process unable to fork a child # (beware the return values of function calls, for they are subtle and + quick to bite your behind)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-16 09:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found