Bloodelf has asked for the wisdom of the Perl Monks concerning the following question:

I am using the following piece of code to pull out all of the strings that end in xls. The problem I have is that I need to define my own scalar (instead of $_) for looking through each line of the array created with readdir(DIR)
@sheets = grep{substr($_,-3) eq 'xls'}readdir(DIR);
Any ideas, my friends?
I know that I could assign readdir(DIR) to an array, and using a foreach command, but I'd prefer it all on one line.......

Replies are listed 'Best First'.
Re: grep using substr
by tadman (Prior) on Jul 06, 2001 at 19:42 UTC
    The $_ inside the grep{} command, and the $_ you might be using otherwise are two different variables, so don't worry about jumping through hoops to elininate it. This is because $_ is declared to be local to the grep BLOCK.
    @sheets = grep{/\.xls$/}readdir(DIR);
    This uses a regexp instead, so you don't even see $_.
Re: grep using substr
by tachyon (Chancellor) on Jul 06, 2001 at 20:39 UTC

    If you want *really* short use a glob:

    $path = 'c:/'; @sheets = <$path*xls>;

    This lets you skip the opendir, readdir, closedir and grep steps.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: grep using substr
by physi (Friar) on Jul 06, 2001 at 21:17 UTC
    Well a oneliner with a foreach, that look's like map

    @sheets = map { $_ if /\.xls$/ } readdir(DIR);
    ----------------------------------- --the good, the bad and the physi-- -----------------------------------

      map() returns a list value consisting of the result of the block or expression for each element of the list supplied in the arguments. When the pattern fails, the return value is still added to the list, so you end up with empty elements in @sheets. grep() is probably a better solution, since it returns a list of only those values for which the block or expression returns a true value.

      If you want to use map(), this might work:

      @sheets = map { /\.xls$/ ? $_ : () } readdir(DIR);

      This will return an empty list if the pattern fails, instead of an empty string, so it won't add empty elements to @sheets.

      Oops: pasted the wrong pattern. Fixed.

Re: grep using substr
by I0 (Priest) on Jul 08, 2001 at 10:30 UTC
    Why do you need to define your own scalar, and why is that a problem?