|
Filtering and altering Perl lists with grep and map
In Perl, you can process whole lists (arrays) in single operations - and that's very efficient at run time as it avoids the needs for loops, and the needed for Perl's Virtual Machine to go back to the byte code (in effect source) for each member.
The map function applies an opertion to each member of a list, and returns a list of the same length, with each element duely mapped. The input to the transform function is $_ - so with embedded calls to functions like uc there's no need to specify it. But if you're going to take 1 off each member then you'll find $_ turn up in the code.
The grep function applies an operation to each member of a list, and returns the member unaltered for inclusion in the output list if the result is a true value. Otherwise, the input member is not included in the output list. So the output list from grep is going to be shorter than the incoming list, but the members themselves won't be modified.
@numbers = (10,30,40,33,45,32,43,22);
# Subtract 1 of each member of @numbers
@numbers = map($_-1,@numbers);
# Return a list of all numbers that are possible days of the month
@digit = grep( $_ <=31 ,@numbers);
print ("@digit\n");
@people = ("tim","steve","JASPER","DaVeY");
# Force all input members to lower case, then capitalise the first letter
@people = map(ucfirst lc,@people);
print "@people\n"; (written 2007-08-23 11:14:03)
Associated topics are indexed under P208 - Perl - ListsP669 - Perl - Data Munging
Some other Articles
Perl for Larger Projects - Object Oriented PerlCustomer feedback - lifeblood of a businessWell House Manor - feature comparison against the old place!2008 course schedule - Perl, Python, PHP, Linux, Java Deployment, Ruby and moreFiltering and altering Perl lists with grep and mapTwo years of campaigning for a train serviceBusiness travel by train in the USATratum TechnologiesSome one line Perl tips and techniquesWhat do people look for on a hotel web site?
|
2259 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|