Definite's Extractor

My findings on Life, Linux, Open Source, and so on.

Tag Archives: glob

Perl glob gotcha: do not rely on glob alone to determine whether files exists

If you, say, writing a ‘ls’ subroutine and write down something like this:

sub ls{
    my ($pattern)=@_;
    for my $f (glob $pattern){
        print "$f\n";
    }
}

If you do

ls "*.txt"

This works, but if you

ls "index.txt"

It always shows “index.txt”, no matter whether “index.txt” exists or not.

This is actually an expected behavior. Consider typing following commands in shell.

gedit *.txt
gedit index.txt

For first one, shell passes all .txt file in current directory to gedit. For second one, shell should pass ‘index.txt’ to gedit, it’s up to gedit to determine what to do with if index.txt does not exist.

So for ‘ls’ like function, following are better:

sub ls{
    my ($pattern)=@_;
    for my $f (glob $pattern){
       if ( -e $f){
           print "$f\n";
       }
    }
}