Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Add space in long string

by lddzjwwy (Novice)
on May 28, 2013 at 12:02 UTC ( #1035576=perlquestion: print w/replies, xml ) Need Help??

lddzjwwy has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have now a long binary string like $bin = 1001100010100001 and I want to change it to sth. like 1001 1000 1010 0001. What is the best way to achieve this? Thanks a lot.

Replies are listed 'Best First'.
Re: Add space in long string
by toolic (Bishop) on May 28, 2013 at 12:22 UTC
      Thank you so much toolic!
Re: Add space in long string
by BrowserUk (Pope) on May 28, 2013 at 12:30 UTC

    Another variation:

    $bin = '1001100010100001';; $bin =~ s[....\K][ ]g;; print $bin;; 1001 1000 1010 0001

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thanks a lot bro! Already got it!
Re: Add space in long string
by jethro (Monsignor) on May 28, 2013 at 12:20 UTC
    $bin=~s/(\d{4})/$1 /g

    Don't ask what happens if the length of your bin string isn't divisible by 4 ;-)

      Haha thanks dude!
Re: Add space in long string
by choroba (Archbishop) on May 28, 2013 at 13:24 UTC
    unpack solution:
    my $bin = '1001100010100001'; print join ' ', unpack '(A4)*', $bin;
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Add space in long string
by johngg (Canon) on May 28, 2013 at 13:29 UTC

    Using substr as an alternative to regex substitution and also grouping in fours from the right-hand side in case that is a requirement.

    $ perl -Mstrict -Mwarnings -E ' sub ins { my $str = shift; my $len = length $str; while ( ( $len -= 4 ) > 0 ) { substr $str, $len, 0, q{ }; } return $str; } say ins( $_ ) for qw{ 1 10 110 1101 10010 101100 1110101 10001011 110100010 };' 1 10 110 1101 1 0010 10 1100 111 0101 1000 1011 1 1010 0010 $

    I hope this is useful.

    Cheers,

    JohnGG

Re: Add space in long string
by hdb (Monsignor) on May 28, 2013 at 13:30 UTC

    Another one starting from right hand side:

    my $bin = '101001100010100001'; $bin = reverse join " ", (reverse $bin) =~ /(.{1,4})/g; print $bin;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1035576]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2020-07-09 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?