Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Write code using less lines

by Anonymous Monk
on Apr 19, 2010 at 16:51 UTC ( #835544=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hey there monks!
I need your wisdom in order to write the following snippet of code using less lines.
The purpose is to count only the letters (not the -) in the given string.
My way is:
$str='ABC---DR----EEEEEGGGG-GRE-RED----KKKK---'; $seq_no_dash=$str; $seq_no_dash=~s/-//g; $len_seq=length($seq_no_dash);

Can I do something in one-line perhaps?

Replies are listed 'Best First'.
Re: Write code using less lines
by toolic (Bishop) on Apr 19, 2010 at 17:03 UTC

      In addition, you could do:

      my $len_seq = $str =~ tr/A-Za-z//;

        Or possibly:

        my $len_seq = $str =~ tr/-//c;
Re: Write code using less lines
by AnomalousMonk (Canon) on Apr 19, 2010 at 17:12 UTC

    Another way, also without modification of the original string, perhaps slightly faster:

    >perl -wMstrict -le "my $str = 'ABC---DR----EEEEEGGGG-GRE-RED----KKKK---'; print qq{'$str'}; my $len = $str =~ tr/A-Za-z//; print qq{'$str'}; print $len; " 'ABC---DR----EEEEEGGGG-GRE-RED----KKKK---' 'ABC---DR----EEEEEGGGG-GRE-RED----KKKK---' 24

      You can save a little typing and also be a little more comprehensive with respect to "anything not a dash" by using the c flag (complement) of tr, see Quote and Quote like Operators.

      knoppix@Microknoppix:~$ perl -E ' > $str = q{ABC---DR----EEEEEGGGG-GRE-RED----KKKK---}; > $len_seq = $str =~ tr{-}{}c; > say $len_seq;' 24 knoppix@Microknoppix:~$

      I hope this is of interest.



Re: Write code using less lines
by nagalenoj (Friar) on Apr 20, 2010 at 06:12 UTC
    This will help you more.
Re: Write code using less lines
by petdance (Parson) on Apr 20, 2010 at 16:58 UTC
    Why is it important to use fewer lines?


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://835544]
Approved by davies
and the sunlight beams...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2017-04-26 06:53 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (469 votes). Check out past polls.