in reply to grep using substr

Well a oneliner with a foreach, that look's like map

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

Replies are listed 'Best First'.
Re: Re: grep using substr
by converter (Priest) on Jul 06, 2001 at 23:49 UTC

    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.