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

Re: Oldie but goodie: glob in scalar context

Thread Previous | Thread Next
From:
Yitzchak Scott-Thoennes
Date:
March 27, 2008 12:37
Subject:
Re: Oldie but goodie: glob in scalar context
Message ID:
46667.71.32.84.230.1206646662.squirrel@webmail.efn.org
On Thu, March 27, 2008 11:28 am, Peter Scott wrote:
> I just found the discussion at
> http://groups.google.com/group/perl.perl5.porters/browse_thread/thread/540
> 1ccdcbd6d4fa1/
> the hard way.  It appears to have petered out and I would like to reopen
> it.
>
> Posit that you are on a large networked filesystem where many user home
> directories are segmented by first letter, e.g., /home/a/alfred,
> /home/x/xavier, etc.  And a user wishes to vet a list of putative
> usernames to see if they have home directories.  A natural solution is:
>
> print "$_ not found\n" unless glob "/home/?/$_" for @putative_users;
>
> Elegant, yes.  Correct, no.  Because when glob() matches the first
> username, on the next call, it will ignore its argument and return undef
> to indicate that it has no more matches for the previous username.
>
> Imagine that user is then trying to use the debugger that you have taught
>  them to use, on an expanded version of this so they can inspect $_
> before the glob call, and they find that when they type
>
> DBG> x glob "/home/?/$_"
>
> it produces a different result from what the program itself does when
> they take the next step.  It's somewhat embarrassing and not a little
> convoluted to explain to them that this is their fault.

Carried to extremes, that argument would banish all context-dependent
behavior.

> I think that scalar glob iteration should be reset when the value of its
> expression changes.  This is what Schwern and chromatic espoused in the
> thread I cite above.

I'm afraid to look in that thread lest I disagree with myself, but at
this time, I feel like this would be sweeping the problem under the
carpet.  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.

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.)


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