tags:

views:

90

answers:

2

In this snippet:

find( sub { 
     print "found " . $File::Find::name . "\n";
     }, ("."));

What type will the (".") be? Array or scalar?

+7  A: 

Let's take a look at the parameters for File::Find::find. The documentation says:

find(\&wanted, @directories_to_search);

Let's think of the find() function written like this:

sub find
{
    my ($wanted, @directories_to_search) = @_;
    ...
}

What you need to realize is that the parameters passed to a function are already in list context (a list of scalars): that's the special variable @_. So when you call find(), the first argument is assigned to $wanted, treated as a coderef (a reference is just a type of scalar). The next variable being assigned to is an array. When you assign a list to an array, the array is "greedy" and takes all values from the list.

So when you assign @_ to ($wanted, @directories_to_search), and all remaining arguments are assigned to @directories_to_search (an array of scalars).

Now let's go back to your code. At the highest level, you're calling find() by passing a list consisting of two terms:

  1. the anonymous coderef sub { ... }
  2. ".": a string of one character in length.

That's like this:

my ($wanted, @directories_to_search) = (sub { ... }, ".");

So find() receives those arguments as I described above: the anonymous coderef is the first argument, and @directories_to_search gobbles the rest:

my $wanted = sub { ... };
my @directories_to_search = ".";

I'm not really sure why you are asking the question (what type is the (".") term), but you can make the call to find() as you have written it above, or you can remove the extra set of parentheses (they don't add anything).

Ether
I was thinking that if I added paranthesis, Perl would just treat it as an array, just like Python or Ruby do when they encounter brackets.
Geo
@Geo: it's already treated as an array by the called function. What are you trying to achieve?
Ether
@Ether: it's not treated as an array. It's just a list.
brian d foy
@brian: yes, sorry, poor choice of words. (That might make a good subject for a SO post.)
Ether
+1  A: 

Read MJD on context.

Sinan Ünür