Uri Guttman wrote:
"JWK" == John W Krahn<jwkr...@shaw.ca>  writes:

   JWK>  Shawn H Corey wrote:
   >>  On 11-03-29 07:50 PM, Noah Garrett Wallach wrote:
   >>>
   >>>  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?
   >>
   >>  s/(\d+)\.(\d+)\.(\d+)\.(\d+)/sprintf('%x:%x:%x:%x::0',$1,$2,$3,$4)/e;

   JWK>  Might be better as:

   JWK>  sprintf '%x:%x:%x:%x::0', /(\d+)\.(\d+)\.(\d+)\.(\d+)/;

   JWK>  So you don't have to use eval.

that works too but don't confuse /e with string eval. in /e the code is
compiled at compile time, not runtime so it is safe and you can't do
anything more dangerous as regular code could. on the otherhand, /ee
(which does work by accident of larry! :) does call string eval on the
result of the replacment expression.

the other difference is that the s///e version replaces the IP with a
hex version and yours needs to be assigned back to the variable. not a
big diff.

and if you are only working on an ip address with no other text, you can
even reduce yours (and the others) to a single (\d+) with /g:

        sprintf '%x:%x:%x:%x::0', /(\d+)/g ;

And if you do it like that you don't even need the capturing parentheses:

        sprintf '%x:%x:%x:%x::0', /\d+/g ;


the s/// could be rewritten like this (note both /e and /g are used):

        $ip =~ s/(\d+)\.?/sprintf('%x:',$1)/eg ;
        $ip .= ':0' ;

here is a working example:

perl -le '$x ="12.23.34.56"; $x =~ s/(\d+)\.?/sprintf("%x:",$1)/eg; print $x'
c:17:22:38:



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

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