CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
perl pack question

 



ningji
Novice

Dec 12, 2012, 8:38 AM

Post #1 of 6 (1613 views)
perl pack question Can't Post

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

Post #2 of 6 (1611 views)
Re: [ningji] perl pack question [In reply to] Can't Post

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


ningji
Novice

Dec 12, 2012, 4:11 PM

Post #3 of 6 (1601 views)
Re: [FishMonger] perl pack question [In reply to] Can't Post

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

Post #4 of 6 (1590 views)
Re: [ningji] perl pack question [In reply to] Can't Post

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

Post #5 of 6 (1578 views)
Re: [ningji] perl pack question [In reply to] Can't Post


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
Novice

Dec 14, 2012, 5:54 PM

Post #6 of 6 (1533 views)
Re: [FishMonger] perl pack question [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives