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

Re: Oldie but goodie: glob in scalar context

Thread Previous | Thread Next
From:
Aristotle Pagaltzis
Date:
March 27, 2008 17:13
Subject:
Re: Oldie but goodie: glob in scalar context
Message ID:
20080328001339.GV22144@klangraum
* Peter Scott <Peter@PSDT.com> [2008-03-28 00:50]:
> At 12:37 PM 3/27/2008, Yitzchak Scott-Thoennes wrote:
>> In point of fact, reusable code which uses scalar-context glob
>> without making sure to exhaust the iterator is buggy. Suppose
>> you have this code instead:
>>
>> sub direxists {
>>   print "checking for $_[0]\n";
>>   print "$_[0] not found\n" unless glob "/home/?/$_[0]"
>> }
>>
>> Your proposed fix would make it work except in the case of
>> being called with the same parameter twice in a row (where the
>> directory does exist), an even harder problem to debug.
>
> Granted, but I think it is at least easier to defend.

Does ease of defense weigh more important than difficulty of
debugging?

> The current behavior is due to the context argument that is
> supplied by perl and unique per lexical instance. Try
> explaining to someone why this:
>
>   print glob("/foo/?") ? "Yes" : "No";
>   print glob("/foo/?") ? "Yes" : "No";
>
> produces a different result from this:
>
>   for (1..2) {
>     print glob("/foo/?") ? "Yes" : "No";
>   }

I always thought these operators needed to return an iterator
object instance instead of effectively using the optree as the
namespace for iterator singletons. I assume Perl 6 does that sort
of thing. But that’s not likely to be fixable in Perl 5.

>> I'd rather see a warning for scalar-context glob not in a
>> while() condition, or something like that. (And even that is
>> buggy if the while loop may be prematurely terminated with
>> last or an exception.)
>
> How about this. An analogous situation is scalar m//g, which
> could get you into trouble if you tried hard enough:
>
>   my $x = "cba";
>   for (qw(a b c))
>   {
>     print "$x matched /$_/\n" if $x =~ /$_/g;
>   }
>
>   cba matched /a/
>   cba matched /c/

That’s not analogous. The scalar /g iterator is tied to a scalar,
not to a node in the optree. A proper analogy would be the
flip-flop operator. Or `each` in scalar context (but that one
can be reset). All of these are kinda broken as designed.

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>

Thread Previous | Thread Next


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