Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Operating on every scalar in a list

Posted by enquirer (enquirer), 9 February 2004
How can I apply an operation to every element in a list without using a loop in my Perl program?

Posted by admin (Graham Ellis), 9 February 2004
Where you can, it's an excellent idea to use Perl's powerful list handling capability to operate on a list as a whole rather than loop through individual elements.  It's quicker at runtime, it saves code, and it saves you the (potential) error of getting your loop counts wrong and starting or finishing early.

The map function in Perl allows you to apply an expression to each member of a list, and it returns a list of the same length, with each new member transformed according to the expression.  When you write the expression, you refer to the incoming value as $_ which is (in any case) the default for many functions.  Thus:
Code:
@to = map(uc."x",@from);

takes all the strings in @from, forces them to upper case with the uc function, and appends a letter "x" to each.  The resultant list is saved in @to.

Sometimes, newcomers get map and grep confused. map returns a list THE SAME LENGTH as the incoming list, with all its elements transformed. grep returns a list which is usually SHORTER than the incoming list, and the elements of this new shorter list are NOT transformed.  i.e. Map is a transformer and Grep is a selector.



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho