Skip Menu |
Report information
Id: 1085
Status: resolved
Priority: 0/
Queue: perl5

Owner: Nobody
Requestors: ilya [at]

Operating System: generic
PatchStatus: (no value)
Severity: medium
Perl Version: (no value)
Fixed In: (no value)

From: Ilya Zakharevich <ilya [...]>
Date: Tue, 27 Jul 1999 17:16:11 -0400 (EDT)
To: thorfinn [...], perlbug [...]
Subject: Re: what should be output of perl -we 'print do { foreach (1, 2) { 1; } }'?
Download (untitled) / with headers
text/plain 245b
If this were true, then Show quoted text
>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
Subject: what should be output of perl -we 'print do { foreach (1, 2) { 1; } }'?
Download (untitled) / with headers
text/plain 1.4k
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.
Download (untitled) / with headers
text/plain 377b
On Tue Jul 15 19:20:10 2003, schwern wrote: Show quoted text
> 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.

This service is sponsored and maintained by Best Practical Solutions and runs on infrastructure.

For issues related to this RT instance (aka "perlbug"), please contact perlbug-admin at