On Tue, Mar 29, 2011 at 19:50, Noah Garrett Wallach
<noah-l...@enabled.com> wrote:
snip
> s/(\d+)\.(\d+)\.(\d+)\.(\d+)/$1:$2:$3:$4::0/
>
> so is there a slick, easily readable way  to get the value $1, $2, $3, $4 to
> be rewriten as  %x instead of a %d?
snip

The [eval regex modifier (e)][0] will let you use an arbitrary
expression for the replacement.  You can then use [sprintf][1] to
print the captures in hexadecimal.  It is important to note that \d
doesn't match what you think it does.  Starting with Perl 5.8, \d
matches and digit character.  This includes characters such as
"\x{1815}" (Mongolian digit five).  To match the ASCII digit
characters you must use [0-9]:

s/([0-9]+)[.]([0-9]+)[.]([0-9]+)[.]([0-9]+)/sprintf
"%02x:%02x:%02x:%02x::0", $1, $2, $3, $4/e;

It is also important to note that, if this is supposed to match an IP
Address, it will match invalid strings like "256.256.256.256".  If you
only want to match numbers between 0 and 255, it can be done using a
regex like this:

my $octet = "(?:[1-9]?0-9|1[0-9]{2}|2[1-4][0-9]|25[0-5])";
s/\b($octet)[.]($octet)[.]($octet)[.]($octet)\b/sprintf
"%02x:%02x:%02x:%02x::0", $1, $2, $3, $4/e;

[0]: http://perldoc.perl.org/perlop.html#s%2fPATTERN%2fREPLACEMENT%2fmsixpogce
[1]: http://perldoc.perl.org/functions/sprintf.html
-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
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