Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Two meanings of undef

by BillKSmith (Monsignor)
on Aug 16, 2020 at 16:07 UTC ( [id://11120816]=note: print w/replies, xml ) Need Help??


in reply to Two meanings of undef

I wish to discuss your second example first. undef is a special 'value'. It is the default value given to a scalar when it is created. It can be assigned later, as you have shown. Its behavior depends on context.

As a number, it is treated as zero. AS a string, it is treated as a null string. As a Boolean, it is treated as 'false'. As a argument to defined, it is the only value for which defined will return 'false'.

?perl -e"$line = undef; print 3 + $line" 3 ?perl -e"$line = undef; print '3' . $line" 3 ?perl -e"$line = undef; print 3 unless $line" 3 ?perl -e"$line = undef; print 3 unless defined $line" 3

Your first example does not do what you think. try it. You probably mean:

$current_time='14:30:05' (undef, $min, $sec)=split /\:/, $current_time

I think of this as an idiomatic use which means exactly what you describe. That field of the assignment is ignored.

Bill

Replies are listed 'Best First'.
Re^2: The three features of undef (renamed)
by LanX (Saint) on Aug 16, 2020 at 16:19 UTC
    > I think of this as an idiomatic use which means exactly what you describe

    It's a documented behavior of list assignments.

    See perldata#List-value-constructors

    Lists may be assigned to only when each element of the list is itself legal to assign to:

    ...

    An exception to this is that you may assign to undef in a list. This is useful for throwing away some of the return values of a function:

    ($dev, $ino, undef, undef, $uid, $gid) = stat($file);

    update

    For the rest: Perl has the symbol undef acting like a constant for the "undefined value" and a builtin function undef(EXPR) to "undefine one variable" which also returns undef to the LHS.

    It might be confusing that they are equally named, but I rarely use the function anyway.

    PS:

    since constants are just special functions in Perl, it could be that undef and undef(EXPR) are implemented in one (magic) operator which does constant folding when called without arguments. But that's an implementation detail, located somewhere between parser and op-tree.

    undef

    Cheers Rolf
    (addicted to the Perl 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://11120816]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-16 22:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found