On Thursday 13 May 2010 07:05:31 C.DeRykus wrote:
> On May 12, 1:15 pm, fulls...@me.com (Brian) wrote:
> > Hi all. I think this should be relatively simple but i just can't figure
> > it out. I have a list of files and directories. The files will all end
> > in .html. All the remaining elements in the list are assumed to be
> > directories. I'm looking for a regex to add a trailing slash to the
> > directories if one doesn't exist. I can do this but using a series of if
> > statements, but I am trying to make my code more concise by using the
> > map function. Here is an example:
> > 
> > my @pages = (
> >         "lc1",
> >         "lc2/",
> >         "lc3/index.html",
> >         "lc4/",
> >         "lc5",
> > );
> > 
> > map {s/(some regex here)/$1\//} @pages;
> 
> Although newer perl versions can use map in void context
> without penalty, it's clearer to use a for loop IMO:
> 
> map { s{ ([^/]) \z }{ "$1/" }xe  if -d } @pages;
> 
> vs.
> 
> for (@pages ) { s{ ([^/]) \z }{ "$1/" }xe  if -d };
> 

Indeed, clarity is the key point here. "map" is intended to generate a new 
list of items from an existing list (possibly to map an array to a different 
array) while keeping the original items intact. "for"/"foreach" are useful 
when you're interested in modifying the elements or for side-effects (like 
printing them).

From the same reason, I prefer to use List::MoreUtils' "any" function (and 
related functions such as "none", "all" and "notall") instead of doing games 
with "if (!grep { .. } )" or List::Util's "!defined(first ...)" - it better 
conveys my intention.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
"Star Trek: We, the Living Dead" - http://shlom.in/st-wtld

God considered inflicting XSLT as the tenth plague of Egypt, but then
decided against it because he thought it would be too evil.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to