Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Write code using less lines

by Anonymous Monk
on Apr 19, 2010 at 16:51 UTC ( [id://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 (Archbishop) 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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-24 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found