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

Im having sequence "CUGUACAGCCUCCUAGCUUUCC" in the file "rna.txt" i need to get the length of the sequence as 22 instead im getting 23. can anyone help me to correct this error?? this is my code:

#!usr/bin/perl use warnings; open (RH, "<rna.txt") || die "cant open the file"; my $arr2 = <RH>; print "rna sequence is $arr2"; $len2= length($arr2); print $len2;

Replies are listed 'Best First'.
Re: calculating length of the string
by Eily (Monsignor) on Jul 29, 2015 at 09:35 UTC

    First, see Writeup Formatting Tips on how to write a nice looking post.

    When it's done, you can look at chomp to remove the extra character at the end of your string ("\n", marking the end of the line)

Re: calculating length of the string
by vinoth.ree (Monsignor) on Jul 29, 2015 at 09:50 UTC
    ++Eily,

    As you read the file content each line ends with newline character '\n', perl has function chomp() it removes characters at the end of strings corresponding to the $INPUT_LINE_SEPARATOR ($/), When given no arguments, the operation is performed on $_.

    use strict; use warnings; my $arr2 = <DATA>; chomp($arr2); print "rna sequence is $arr2\n"; my $len2= length($arr2); print $len2; __DATA__ CUGUACAGCCUCCUAGCUUUCC

    All is well. I learn by answering your questions...

      ... and, just to be 100% clear, the bit o’ magick that you would be looking for, in the above code snippet, is the call to chomp().