[ILUG] OT perl Q

Niall O Broin niall at linux.ie
Fri Aug 10 14:23:23 IST 2001


On Fri, Aug 10, 2001 at 12:32:49PM +0100, JustinMacCarthy wrote:

> Hi all, I'm just writting a perl script to dump a file in HEX I came across
> this, which does what I want but can someone explain this line to me ? or
> write it differently ?
> 
>         for(map ord, split // , $buf)

What this line does is split $buf into individual characters and then uses
the map function to apply the ord function to each of those characters - ord
turns its argument into its numeric value i.e. A -> 0x41 (65) etc. But it's
Perl, whose motto is TMTOWTDI (There's More Than One Way To Do It) :-) so you
could replace

>     for(map ord, split // , $buf)
>     {
>         printf "%02x ",$_;
>     }

by 

+     for(split // , $buf)
+     {
+         printf "%02x ", ord $_;
+     }

or

+     for(split // , $buf)
+     {
+         printf "%02x ", ord;
+     }

or for a different approach

+     for(0..length($buf)) {
+         printf "%02x ", ord substr, $buf $_, 1;
+     }


but map is a Perlier way of doing it. There's probably an even Perlier way
using pack or unpack, but for some reason those functions always hurt my
head and I've never been able to find a nice tutorial on their use. I can
usually get them to do what I need but it's not always obvious why (and no,
don't bother saying that that's the whole trouble with Perl anyway :-) )





Niall




More information about the ILUG mailing list