On May 11, 2012, at 7:39 PM, Owen wrote:

> I found this on the internet to convert an IPv4 address (w.x.y.z) to
> a decimal number.
> 
> w * 16,777,216 + x * 65,536 + y * 256 + z = decimalNumber
> 
> I then found the subroutine, ip2dec in the script below.
> 
> The script works, that's not my problem. The problem is "How does it
> work"? 
> 
> The "split /\./" I understand. I've looked at perldoc pack and sort of
> see it is taking the ip4 address, packing it up and then unpacking.
> 
> But what's with these "=>" things? How is that routine meant to read?
> 
> 
> TIA
> 
> 
> Owen
> 
> ========================================================
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> 
> my $Originator = '127.0.0.1';
> 
> $Originator = ip2dec($Originator);
> 
> my $stored = 'stored';
> $stored = "$stored$Originator";
> 
> sub ip2dec {
>    return unpack N => pack CCCC => split /\./ => shift;
> }
> 
> print "$stored\n";

Perl will interpret the '=>' operator as a "fat comma", which also has the 
side-effect of stringifying a word to its left.

Therefore, the return line will be interpreted as:

   return unpack( 'N', pack( 'CCCC', split( /\./, shift)));

So the argument passed to the subroutine is split at '.' characters, yielding 
four substrings ('127','0','0','1'). These are interpreted as four unsigned 
char values and packed into a string, which is then interpreted as an unsigned 
long 32-bit value and returned.
 
In my opinion, this is a case of someone being too clever and just trying to 
show off. You shouldn't program like that.




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to