Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

oneliner to count the number binary digits in this string 1011111

by suvendra123 (Initiate)
on Mar 12, 2021 at 22:44 UTC ( [id://11129541]=perlquestion: print w/replies, xml ) Need Help??

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

This node falls below the community's minimum standard of quality and will not be displayed.

Replies are listed 'Best First'.
Re: oneliner to count the number binary digits in this string 1011111
by LanX (Saint) on Mar 12, 2021 at 22:51 UTC
       $string_len    = length($binary_number);

        DB<45> p "NOPE! 1011111" =~ tr/01// 7 DB<46> p length "NOPE! 1011111" 13 DB<47>

        > to count the number binary digits

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

Re: oneliner to count the number binary digits in this string 1011111
by BillKSmith (Monsignor) on Mar 13, 2021 at 16:31 UTC
    If you know that the string contains only binary digits, use length('1011111'). Use LanX's method if you wish to ignore non-binary characters.
    Bill
Re: oneliner to count the number binary digits in this string 1011111
by davido (Cardinal) on Mar 13, 2021 at 21:34 UTC

    Where is your attempt?


    Dave

Re: oneliner to count the number binary digits in this string 1011111
by AnomalousMonk (Archbishop) on Mar 14, 2021 at 22:02 UTC

    LanX's use of the tr/// operator (see perlop) is best (simplest, fastest) for simple counting.

    For counting in cases of more complex matching, m// (perlop) can be used:

    Win8 Strawberry 5.8.9.5 (32) Sun 03/14/2021 17:12:13 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings my $s = '1010011 f1e f0o g0e'; my $n =()= $s =~ m{ (?<= [fg]) [01] (?= [oe]) }xmsg; print "$n [01] in '$s' \n"; ^Z 3 [01] in '1010011 f1e f0o g0e'
    See goatse (don't ask) for a discussion of the =()= "operator."


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2025-12-11 11:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (92 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.