[Omaha.pm] Tighter/cleaner way to do this? map { grep {} } ?

James Harr jharr at ist.unomaha.edu
Thu Feb 5 11:09:30 PST 2009


If you're dealing with large amounts of resultant data, it might be
better not to copy and print, but rather just print in the loop.

$first = 1;
foreach(@a){
	next unless /(gold\w+)/;
	print ", " unless $first;
	$first = 0 if $first;
	print $1;
}

If it's small amounts of data, you can make it even shorter:
  print join ", ", map { /(gold\w+)/ } @a;
  print "\n";

--
James Harr <jharr at ist.unomaha.edu>
402-554-3340
Assistant Research Systems Manager 
College of Information Science and Technology
University of Nebraska at Omaha


-----Original Message-----
From: omaha-pm-bounces+jharr=ist.unomaha.edu at pm.org
[mailto:omaha-pm-bounces+jharr=ist.unomaha.edu at pm.org] On Behalf Of Jay
Hannah
Sent: Thursday, February 05, 2009 12:29
To: Perl Mongers of Omaha, Nebraska USA
Subject: Re: [Omaha.pm] Tighter/cleaner way to do this? map { grep {} }
?

Ooo... cool. 


Old code:

my @b;
foreach (@a) {
   if (/(gold\w+)/) {
      push @b, $1;
   }
}


New code:

my @b = map { /(gold\w+)/ } @a;


map gets the matches only ($1), not the entire original string.  :)

j

_______________________________________________
Omaha-pm mailing list
Omaha-pm at pm.org
http://mail.pm.org/mailman/listinfo/omaha-pm


More information about the Omaha-pm mailing list