On Dec 8, 2003, at 11:28 AM, Jeff Westman wrote:

[EMAIL PROTECTED] wrote:

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.

The first line is better written as


opendir(DIR, $some_dir) or die "can't opendir $some_dir: $!";

Note the use of 'or' instead of '||'. Precedence is extremely important,
especially in perl where so much of the code can be "short-circuited".

Changing the || to or in the above line has no effect. However, as Jeff said, parens in Perl are often optional on subroutine calls and if we leave those out:


opendir DIR, $some_dir or die "can't opendir $some_dir: $!";

We get the traditional Perl open() call and here it matters if we use || or or. Why do we write it like that? We like the way it reads.

Its that line with the grep in it.
grep is obviously a built-in perl function.

This is something I've seen before ...
the output of the function readdir is "trickling down" to become the
input of the function grep ?

One minor problem, there is a comma missing before the 'readdir':


@dots = grep { /^\./ && -f "$some_dir/$_" }, readdir(DIR);

The line compiles fine. The block version of grep() does not require a comma.


perldoc -f grep

No, you would use a while or for loop and then search for files not beginning
with a dot.

So while-readdir, search for files (only) and test if they DONT begin with a dot, then store them into an array. Now that we have the

You say this twice, but that still doesn't make it true. I think you need to reread that grep() call. ;) We're searching for files that DO begin with a dot here and placing them in the fitting @dots array.


If that is so, what is all that business with the curly braces ?
I thought curly braces are supposed to denote code sections ?

This is correct, it's a "chunk of code". It will be executed once for each item returned by readdir().


p.s. It seems some of my confusion comes from the fact that I am used to
putting () around funtion calls. That still doesn't help with the curly
braces though ... %^)

Parens are often optional. When in doubt, use them. I never use them in
simple print statemtents, but some functions like 'split', it just makes more
sense.

I think the easiest rule to start learning with in use parens for your own subs and leave them off of built-ins, except when you need them to clarify/enforce precedence.


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