Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Insert colons into a MAC address

by Not_a_Number (Prior)
on Jan 13, 2012 at 23:30 UTC ( [id://947850]=note: print w/replies, xml ) Need Help??


in reply to Insert colons into a MAC address

but I would prefer a regex

Any particular reason? If you're thinking of input validation, how about:

$_ = '525400eb8b36'; die "Invalid input\n" if length != 12 or /[^[:xdigit:]]/; print join ':', unpack '(A2)*';

Alternatively, use a CPAN module:

use Net::MAC; print Net::MAC->new( mac => '525400eb8b36' )->as_Sun();

Replies are listed 'Best First'.
Re^2: Insert colons into a MAC address
by xyzzy (Pilgrim) on Jan 14, 2012 at 09:13 UTC

    I remember when I used to think why on earth would I use a whole module if I'm just doing this one thing that can clearly be done using the built-in features of Perl. Boy, was I an idiot.


    $,=qq.\n.;print q.\/\/____\/.,q./\ \ / / \\.,q.    /_/__.,q..
    Happy, sober, smart: pick two.
      Well, I think I'll choose this:

      $mac =~ s/([0-9a-fA-F]{2})\B/$1:/g;

      which can be also spelled as:

      $mac =~ s/(\p{Hex}{2})\B/$1:/g;

      The [:xdigit:] class does not work (I don't know why).

      @Not_a_Number: probably there isn't a reason to prefer a regex over 'unpack' or the use of a module, in this case, since this regex is not really more readable than other methods.
      Anyway I'm more familiar with regexes than with unpack or the Net::MAC module, so there is a chanche that I will recognize and understand that sooner when looking again at my code in the future.
      As for modules, I often avoid (or completely overlook) them, because I usually have little or no control on the systems I work onto (so installing a module can be a tricky or impossible task). I see that "use a module" vs "reinvent the wheel" is an ever discussed problem. I'm on the "reinvent the wheel" side, but it's not my fault :)

      Thanks to all, bye.

      Edit:
      jut in case someone come here in the future.

      [:xdigit:]

      actually works:

      $mac =~ s/([[:xdigit:]]{2})\B/$1:/g;

      I just didn't put enough square brackets. [:xdigit:] is equivalent to [:xdigt] (literally), while [[:xdigit:]] is equivalent to [0-9a-fA-F]. Reading the f. manual helps as usual :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://947850]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-20 03:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found