Why does undef->{id} give a warning and $undefined_var->{id} doesn't

H

himanshu.garg

% cat test.pl
use Test::Simple tests => 2;
use strict;
my $undefined_var;
ok(!$undefined_var->{id}, '!$undefined_var->{id}');
ok(!undef->{id}, '!undef->{id}')

% perl test.pl
1..2
ok 1 - !$request->{id}
Can't use an undefined value as a HASH reference at test.pl line 5.
# Looks like you planned 2 tests but only ran 1.
# Looks like your test died just after 1.
 
I

Ivan Novick

% cat test.pl
use Test::Simple tests => 2;
use strict;
my $undefined_var;
ok(!$undefined_var->{id}, '!$undefined_var->{id}');
ok(!undef->{id}, '!undef->{id}')

% perl test.pl
1..2
ok 1 - !$request->{id}
Can't use an undefined value as a HASH reference at test.pl line 5.
# Looks like you planned 2 tests but only ran 1.
# Looks like your test died just after 1.

Try running this code:

###########################
use strict;
my $x = undef;
print "$x\n";
$x->{id} = 3;
print "$x\n";
###########################

You will see $x starts as undefined but perl will create a hash when
you try to assign something to a $x->{id}. As Tad, said, they call
that autovivification which means "to bring oneself to life".

The second time you print $x it has a memory address.

You can not do the same by directly using undef as the address of a
hash because that is not a scalar variable that can hold the address
of a created hash and thus its illegal syntax.

Regards,
Ivan Novick
http://www.0x4849.net
 
H

himanshu.garg

Try running this code:

###########################
use strict;
my $x = undef;
print "$x\n";
$x->{id} = 3;
print "$x\n";
###########################

You will see $x starts as undefined but perl will create a hash when
you try to assign something to a $x->{id}. As Tad, said, they call
that autovivification which means "to bring oneself to life".

The second time you print $x it has a memory address.

You can not do the same by directly using undef as the address of a
hash because that is not a scalar variable that can hold the address
of a created hash and thus its illegal syntax.

Regards,
Ivan Novickhttp://www.0x4849.net

Yes,

Got it now. Couldn't have been explained better.

Thank You,
Himanshu.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top