Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of sumdeus (4830)

Wednesday February 18, 2004
07:55 AM

map, pack, and grep

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

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.

Good old binary to decimal for all you CS monkeys.

sub bin2dec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));

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?

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • 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
  • 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");
      my @row = map { { name => $_ } } @{ $sth->{NAME_lc} };
      my $record = { column => \@row };
      my @values = map { \$_->{content} } @row;
      $sth->bind_columns( @values );