Definite's Extractor

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

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";
       }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: