Roman Hanousek wrote:
> #Start test.pl

use warnings;

> use strict;
> 
> # test.pl is saved in c:/work/temp
> my $testDir = "c:/work/temp";
> 
>    opendir(DIR, $testDir );

You should *always* verify that the directory was opened successfully.

opendir DIR, $testDir or die "Cannot open directory '$testDir' $!";

>       my $file = grep { /st.pl$/ } readdir(DIR);

The '.' character is special in a regular expression.  To match a literal
period character you need to precede it with a backslash.

my $file = grep /st\.pl$/, readdir DIR;

>    closedir(DIR);
> 
>    print "blah1: [[[" .  $file ."]]]\n" ;
>    print "blah2: [[[" .  "$file" ."]]]\n" ;
>    
>    opendir(DIR, $testDir );
>       my @file = grep { /st.pl$/ } readdir(DIR);
>    closedir(DIR);
> 
>    print "blah3: [[[" .  @file ."]]]\n" ;
>    print "blah4: [[[" .  "@file" ."]]]\n" ;
> #End test.pl
> 
> 
> The result ends up being:
> 
> C:\>perl c:\work\temp\test.pl
> blah1: [[[1]]]
> blah2: [[[1]]]
> blah3: [[[1]]]
> blah4: [[[test.pl]]]
> 
> Could any one explain why I am getting the different results.

Sure.

> I would thought that I would get the file name back in all instances of blah 
> not
> just blah4 and why does it only work when @file is surrounded by quotes.

perldoc -f grep
     grep BLOCK LIST
     grep EXPR,LIST
           This is similar in spirit to, but not the same as, grep(1) and its
           relatives.  In particular, it is not limited to using regular
           expressions.

           Evaluates the BLOCK or EXPR for each element of LIST (locally
           setting $_ to each element) and returns the list value consisting
           of those elements for which the expression evaluated to true.  In
                                                                          ^^
           scalar context, returns the number of times the expression was
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
           true.
           ^^^^^


In blah1 and blah2 you are assigning to a scalar variable so grep returns a
number for the times that the regular expression matched.

In blah3 you are using the concatenation operator (.) which forces scalar
context so the array is evaluated in scalar context which is the number of
elements in the array.

print "blah3: [[[" .  @file . "]]]\n";

Is the same as:

print "blah3: [[[", scalar @file, "]]]\n";

In blah4 you are interpolating the array in a string.

print "blah4: [[[" . "@file" . "]]]\n";

Is the same as:

print "blah4: [[[" . join( $", @file ) . "]]]\n";




John
-- 
use Perl;
program
fulfillment

-- 
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