defined() confusion

C

Chris

This seems inconsistent:


#!/usr/bin/perl -w

use strict;

my @y;
if(!defined(@y))
{
print "y undefined\n";
}

my $z = scalar(@y);
if(!defined($z))
{
print "z undefined\n";
}

if(!defined(scalar(@y)))
{
print "scalar(\@y) not defined\n";
}



This prints

y undefined
scalar(@y) not defined

So, the question is, why does

my $z = scalar(@y);
if(!defined($z))

behave differently from

if(!defined(scalar(@y)))

???

Thanks,
Chris
 
A

Alex Zeng

When the value is assgined to a variable, it is upgraded, which explain the
outcome.

When a variable is created, it has a undef value. It is not "", not 0, not
(), but undef. When assiging the undef value to another variable, perl pick
the upgrade according to the context, therefore,
-------------
my @y,
if (@y) {
}
@y will be intepreted as 0 instead of undef, a upgrade undef => 0 happens
since the context asks for a boolean

my $z = scalar(@y);
Here z is assigned an upgraded version of the value, that would be "" or 0.
 
N

nobull

This seems inconsistent:

It is.
#!/usr/bin/perl -w

use strict;

my @y;
if(!defined(@y))

defined() applied to agregate types does not tell you anything useful
to a Perl programmer. (What it actually tells you is if an AV has been
assigned. This may be of interest to a perl programmer but is of no
interest to a Perl programmer).
So, the question is, why does

my $z = scalar(@y);
if(!defined($z))

behave differently from

if(!defined(scalar(@y)))

The handling of the scalar() function by the compiler is rather odd.
It often gets eleminated from the parse-tree in situations where it
doesn't do anything. Sometimes however the complier is over zealous
and eleiminates it in places where it doesn't do anything useful but
should, by rights, do something. This can lead to a number of odd
effects (including that above).

Obiously if the compiler were fixed and scalar() was not eliminated
the defined(scalar(@y)) would always be true so there's not much
insentive to fix this bug.

This newsgroup does not exist (see FAQ). Please do not start threads
here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top