I have to create a script to look for files matching a particular extension and store the name(s) of the files for use later on in a script. Is there any advantage or disadvantage of using GLOB or GREP? They both seem to do the same thing:

GLOB

Perl

# Define an array@files=glob("*.txt");# files matching this extensionforeach$file(@files){print"$file\n";# Do something}

Yes, since you're making the interpreter sort through the list instead of just using the native readdir function. I'd only suggest using grep if you need to search within an array itself, that's why glob is there, it does all the other heavy lifting for you :)

And hey, that's best answer material, that's an exact answer :P

I'm surprised to see a Perl question, I used Perl for about a decade, but I haven't in about 7 years or so, it's unfortunate it isn't as popular was it once was.

5 Replies

glob is strictly for listing files (by pattern, name list, type, etc), but grep searches within an array for a given pattern. Basically in your examples, glob would be a shorter version of how you're using grep, because you're using glob to populate an array (with readdir) which grep is then filtering for .txt. You can use grep for any sort of array you want, but you can only use glob for file listing, and unlike readdir, glob allows you to pre-filter, you can use regex or even use the traditional '*.txt' string, and search for multiple types with a space '*.txt *.c *.h'

glob is strictly for listing files (by pattern, name list, type, etc), but grep searches within an array for a given pattern. Basically in your examples, glob would be a shorter version of how you're using grep, because you're using glob to populate an array which grep is then filtering for .txt.

Yes, since you're making the interpreter sort through the list instead of just using the native readdir function. I'd only suggest using grep if you need to search within an array itself, that's why glob is there, it does all the other heavy lifting for you :)

And hey, that's best answer material, that's an exact answer :P

I'm surprised to see a Perl question, I used Perl for about a decade, but I haven't in about 7 years or so, it's unfortunate it isn't as popular was it once was.

Yes, since you're making the interpreter sort through the list instead of just using the native readdir function. I'd only suggest using grep if you need to search within an array itself, that's why glob is there, it does all the other heavy lifting for you :)

And hey, that's best answer material, that's an exact answer :P

I'm surprised to see a Perl question, I used Perl for about a decade, but I haven't in about 7 years or so, it's unfortunate it isn't as popular was it once was.

The process I'm tweaking unfortunately still relies on Perl as it's main language due to legacy Unix support. I would prefer PowerShell but the application cannot use that language, only Perl and Batch.