Bitten by glob crypto context

grinder on 2007-09-27T11:05:09

/me is annoyed

I just spent a while chasing a stupid bug. I have an big log directory that I have to clean up. The number of files caused the shell's wildcard expansion to fail. So I wrote some perl to move things around.

And it didn't do anything. To cut a long story short, I needed the total number of files in the directory. So I had something along the lines of:

perl -le 'print scalar(glob("*"))'

That does not return the number of files. It returns the name of the first file. Or the last. I don't care.

You have to force array context and throw it away:

perl -le 'print scalar(()=glob("*"))'

This prints 31192. I wish Perl didn't do this. Nice interview question though, I guess.


while ...

runrig on 2007-09-27T14:42:05

In scalar context, it's an iterator, like readline, returning the first thing on the first call, then the next thing, etc., so you can do:

while (my $file = glob("*")){
  print "$file\n";
}

Uhm, no

Aristotle on 2007-09-27T22:33:24

Language lawyer questions do not a good interview question make.

Re:Uhm, no

phaylon on 2007-09-28T01:07:27

Though it might be a nice question for giving extra points if you ask it like "Why could this be?"

Re:Uhm, no

grinder on 2007-09-28T12:01:15

You are perfectly correct.

(Note to self: refrain from sarcasm when writing).

Re:Uhm, no

Aristotle on 2007-09-28T15:30:27

Heh. I was 40/60 on whether you were serious or not.

it's not "crypto context"

merlyn on 2007-09-30T14:10:25

You just need to get out of your head the notion that "list in list context means length of same list in scalar context". It's a bad model. In fact, there are more things that don't return the count than do. So you just learn each one individually, and all of it makes sense.