map, pack, and grep

sumdeus on 2004-02-18T12:55:24

Just looking over a couple of functions that are often overlooked in normal programming practices, especially by people new to perl.

MAP:
Each element need not necessarily map to a single item. If multiple values are created, map returns them all as a single, flattened list. For example, you could split all words in all phrases into a single list:

@words = map split, @phrases;


Map is such a nice function to keep in mind for saving time.

PACK:
Good old binary to decimal for all you CS monkeys.
sub bin2dec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
GREP:
Weeding out comments, as taken from perldoc -f grep
@foo = grep(!/^#/, @bar);
What are you favorite overlooked functions? Anyone have any interesting and innovative uses of the map function?


Nice generalization of map

VSarkiss on 2004-02-18T16:49:15

Anyone have any interesting and innovative uses of the map function?
Take a look at mapcar from Tye McQueen. I see he also uploaded an even more generalized version to CPAN as Algorithm::Loops

Re:Nice generalization of map

sumdeus on 2004-02-18T16:59:49

Thanks, that's awesome. It's nice to see some of the better functions of LISP available in Perl.

My latest fun use of map: DBI to XML

runrig on 2004-02-18T20:01:52

I came up with this to dump database tables to XML (using DBI and XML::Simple):
  my $xs = XML::Simple->new(rootname => 'record', suppressempty => undef);
...
  print qq!<TABLE name="$table">\n!;
  my $sth = $dbh->prepare("select * from $table");
  $sth->execute;
  my @row = map { { name => $_ } } @{ $sth->{NAME_lc} };
  my $record = { column => \@row };
  my @values = map { \$_->{content} } @row;
  $sth->bind_columns( @values );
  while ($sth->fetch) {
    defined $$_ or $$_ = '' for @values;
    print $xs->XMLout($record);
  }
  print "</TABLE>\n";
It'll get even shorter (e.g. the 'defined' line will go away), if grantm ever releases the next version of XML::Simple and remembers to include my patch :-)

Re:My latest fun use of map: DBI to XML

sumdeus on 2004-02-22T18:15:12

It took me a couple of minutes to digest this, but after looking through everything it does, I think I have learned something, and that's what it is all about isn't it? I appreciate the little snippet. Thanks!