Home: Perl Programming Help: Beginner:
perl pack question



ningji
User

Dec 12, 2012, 8:38 AM


Views: 3542
perl pack question

say i have a string "0001001101111111",
want to convert it into
"0001-0011-0111-1111",

i can unpack it with "A4" x 4,
then use a for loop to join them.

but thought there's another quick easy way (shift ?) to avoid for loop.
any suggestions ?

thanks !


FishMonger
Veteran / Moderator

Dec 12, 2012, 9:10 AM


Views: 3540
Re: [ningji] perl pack question

See: perldoc -f join
http://perldoc.perl.org/functions/join.html


ningji
User

Dec 12, 2012, 4:11 PM


Views: 3530
Re: [FishMonger] perl pack question

sorry i didn't get the full answer yet.

i can use join,
but if the string changes, some times 12 bits, sometimes 16 bits,
then i can use for loop.

is there a way to avoid it ?


In Reply To



Laurent_R
Veteran / Moderator

Dec 12, 2012, 11:17 PM


Views: 3519
Re: [ningji] perl pack question

What about trying this:


Code
s/([01]{4})/$1-/g;



(This post was edited by Laurent_R on Dec 13, 2012, 10:46 AM)


FishMonger
Veteran / Moderator

Dec 13, 2012, 6:36 AM


Views: 3507
Re: [ningji] perl pack question


Code
use strict; 
use warnings;

my @str = qw( 0001001101111111 000100110111 );

for ( @str ) {
print join('-', unpack("A4" x (length($_)/4))), $/;
}


outputs:
c:\testing>ningji.pl

Quote
0001-0011-0111-1111
0001-0011-0111



ningji
User

Dec 14, 2012, 5:54 PM


Views: 3462
Re: [FishMonger] perl pack question

Thanks everyone, this is cool,
i like Laurant's answer most.