Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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?

Comment on Write code using less lines
Download Code
Re: Write code using less lines
by toolic (Chancellor) 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 (Abbot) 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.

      Cheers,

      JohnGG

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?

    xoxo,
    Andy

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2015-01-29 09:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My top resolution in 2015 is:

















    Results (232 votes), past polls