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:  <%-{-{-{-<