in reply to Unshift and push inside of map operation.

In my opinion (or "I personally believe" if you must) modifying an array with push/pop inside a map statement is one of those hints that there's a better way to go about a problem! :-)

The canonical form of map (according to me) is used to return a mapped version of the input:

@a = map { # A function of $_, eg: $_ . ".txt" } @a;
One of the things I find particularly useful is that the block of code can evaluate to a list, including an empty one. Ie the output of map need not be the same length as the input. Eg
# Emulate grep with map @a = map { elementShouldBeIncluded($_) ? $_ : () } @a; # Double up the list @a = map { ($_, $_) } @a;

In this particular case, this feature may be exactly what you're after, depending on how what exactly your vendor supplied program does. Consider the following structure:

@a = map { # Is it a dir? (-d $_) ? # Expand it (somehow) into a list of files turnDirIntoFilesUsingVendorProg($_) : # It's a file - pass it straight through $_ } @a;
Hope that helps.

Replies are listed 'Best First'.
Re^2: Unshift and push inside of map operation.
by juster (Friar) on Sep 23, 2008 at 19:15 UTC

    The map solution was so cool and perlish that I had to try recursion with it!

    sub perlish { chomp; $_ = realpath($_); # follows links, makes full path ( -d ) ? ( $processed{$_} ? () : do { my $basedir = $_; $processed{$_} = 1; # prevent infinite recursion into link +s # turn results of ls into relative paths before recursion # and avoids using chdir map &perlish, ( map {"$basedir/$_"} `ls $_` ); } ) : $_; } %processed = ( getcwd() => 1 ); print join "\n", (map &perlish, `ls`),"\n";

    I love recursive maps now! It is MUCH prettier if you don't have to worry about symbolic links to dirs you already checked or relative paths:

    sub perlish { chomp; ( -d ) ? map &perlish, `find $_/* -maxdepth 0` : $_; } my @files = map &perlish, `find . -maxdepth 0`;