On Dec 8, 2003, at 10:52 AM, [EMAIL PROTECTED] wrote:

I've just started trying to pick up a little perl.
I'm breezing through "Learning Perl" and reading the perl docs.

Here is some syntax I found a little funny, and I was hoping somebody
could explain this too me:

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

The first and 3rd lines I have no problem with.

Its that line with the grep in it.

Okay, let's go step by step readdir() is called (in list context), so it returns all entries in the directory. Simple enough.


That returned list is immediately fed to another built-in, grep(). grep() goes through every element in the list, checking it against some expression you provide (the part in the braces). Inside the expression, the element you're currently checking is in Perl's default variable $_. If the expression returns true for that element, it is included in grep()'s return list. If not, it is omitted.

In this case, the expression check two things. First, it uses a pattern match on the name to see if it begins with a dot (.). If it does, it checks to make sure the entry is a file, to rule out entries like '.' and '..'. If the entry passes both tests, grep() returns it. Otherwise, it's let out of the return list. It may help to think of grep() as a filtering engine you can use to build on-the-fly lists.

Finally, the list returned by grep() is assigned to @dots, which is pretty much what it will contain, any file beginning with a dot (hidden files on a Unix system).

Here's a rough English translation of the line:

place in @dots all things beginning with . that are actually files from the listing for DIR

Hope that helps.

James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to