develooper Front page | perl.perl5.porters | Postings from August 2008

[perl #54962] BUG with ARRAY

From:
Bram via RT
Date:
August 11, 2008 03:29
Subject:
[perl #54962] BUG with ARRAY
Message ID:
rt-3.6.HEAD-29762-1218446372-639.54962-14-0@perl.org
On Wed May 28 02:17:56 2008, kes-kes@yandex.ru wrote:
> In perl is pretty good default behaviour to create define empty
> hash/array if it is on right side like this:
> print $hash->{array}->[7]

This will autovivify $hash->{array}.
This because it needs an array before it can access the 7th element in 
it.

> print @{ undef }[0];

This does not do what you think.
I suggest you enable warnings and/or strict.

perl -wle 'print @{ undef }[0];'
Ambiguous use of @{undef} resolved to @undef at -e line 1.
Scalar value @{ undef }[0] better written as ${ undef }[0] at -e line 1.
Name "main::undef" used only once: possible typo at -e line 1.
Use of uninitialized value in print at -e line 1.


What you wrote is the same as: print $undef[0]


> print( ( undef )[1] ); 

This is a list slice.
(undef) is the list, [1] is the index in it.
There is only 1 element (highest index 0) so it prints nothings.

print( ( undef, "a" )[1] ); will print "a" for example.

> # But this does not work? =>>>> print ( undef )[1];
$ perl -wle 'print ( undef )[1];'
print (...) interpreted as function at -e line 1.
syntax error at -e line 1, near ")["
Execution of -e aborted due to compilation errors.

A function returns a list. You can not directly use a list slice on a 
function call.

What you wrote is:

(print (undef))[1]

Which is the same as

perl -wle 'sub s1 { return "a", "b"; }; my $x = s1()[1];print $x;'
syntax error at -e line 1, near ")["
Execution of -e aborted due to compilation errors.

vs

perl -wle 'sub s1 { return "a", "b"; } my $x = (s1())[1];print $x;';
b

> 
> 
> but why this rule does not take
> effet for function:
> sub test { return undef; }
> print test()->[0];

test() returns a list of one element, undef.
Then you try to use an undefined value as an array reference.
That doesn't work.

> print @{ test() }[0];

Again an undefined value as an array reference. 


This all behaves as documented an expected.


Kind regards,

Bram



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About