Perl / perl5

🐪 The Perl programming language
https://dev.perl.org/perl5/
Other
1.94k stars 554 forks source link

what should be output of perl -we 'print do { foreach (1, 2) { 1; } }' #265

Closed p5pRT closed 15 years ago

p5pRT commented 25 years ago

Migrated from rt.perl.org#1085 (status was 'resolved')

Searchable as RT1085$

p5pRT commented 25 years ago

From ilya@math.ohio-state.edu

If this were true\, then

perl -we "print do { 17; foreach (1\,2) { 1; } }"

would print 17. But it prints

  Useless use of a constant in void context at -e line 1.

I consider this (no return of foreach) as a bug\, and report it as such.

Ilya

p5pRT commented 21 years ago

From @schwern

If Data​::Dumper is to be believed\, it returns an empty string.

$ perl -MData​::Dumper -wle "@​a = do { foreach (1\,2) { 1; } }; print Dumper \@​a" $VAR1 = [   ''   ];

Different from an empty do block.

$ perl -MData​::Dumper -wle "@​a = do { }; print Dumper \@​a" $VAR1 = [];

This explains why do { 17; foreach ... } complains about a useless constant.

A while loop returns 0.

$ perl -MData​::Dumper -wle '$foo = 42; sub foo { $bar = 2; $foo++; while ($bar--) { 1; } } print Dumper [foo]' $VAR1 = [   0   ];

Changing this behavior can cause serious backwards compat issues. Consider the options​:

1) Have foreach be "null" so the statement before it is what is returned from the block.

That will alter subroutines such as​:

  sub foo {   $foo++;   foreach (...) { ... }   }

Currently this will return an empty string. If we change the foreach behavior\, it will return the value of $foo.

2) Have foreach return its last evaluated expression in its block.

Similar problem. Any subroutine ending in a foreach loop will suddenly start returning values.

I suppose it should be documented\, but at this point it would likely be better to simply declare it undefined rather than paint ourselves into a corner by documenting that it returns false. Perhaps to say simply that for purposes of the "last evaluated expression" rule\, a loop is an expression and its value is undefined.

p5pRT commented 15 years ago

From skasal@redhat.com

On Tue Jul 15 19​:20​:10 2003\, schwern wrote​:

A while loop returns 0.

Actually\, that has changed​: in my perl-5.10.0\, while loop returns an empty string as well.

So the situation is more consistent now.

It's almost ten years since the ticket was started\, almost 6 years since it was noted that foreach returns an empty string. Let's call it a tradition and close the ticket.

p5pRT commented 15 years ago

skasal@redhat.com - Status changed from 'open' to 'resolved'