Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Length of strings in an array

by shabird (Sexton)
on Sep 20, 2020 at 16:13 UTC ( [id://11121963]=perlquestion: print w/replies, xml ) Need Help??

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

I wrote a program that asks the user for four strings. Thereafter, derive the length of these four strings and store the lengths in an array. Next, I want to print out the lengths in sorted order to the terminal. Below is the program for this task

#!/usr/bin/perl -w use warnings; print "Please enter first DNA sequence\n"; $firstDna = <STDIN>; $frstLength = length($firstDna); print "Please enter second DNA sequence\n"; $secondDna = <STDIN>; $scndLength = length($secondDna); print "Please enter third DNA sequence\n"; $thirdDna = <STDIN>; $trdLength = length($thirdDna); print "Please enter fourth DNA sequence\n"; $fourthDna = <STDIN>; $frthLength = length($fourthDna); @array = sort($frstLength, $scndLength, $trdLength, $frthLength); print "Your Dna sequence length is: @array";

I have 2 problems with this code first is it gives the length of the string but it also counts the enter key for example if i type a string of 6 characters it gives me the length 7. and second the order is not sorted although i have used to sort function for that. Please help me with this problem thank you in advance :)

Replies are listed 'Best First'.
Re: Length of strings in an array
by Athanasius (Archbishop) on Sep 20, 2020 at 16:27 UTC

    Hello shabird,

    it gives the length of the string but it also counts the enter key

    You should chomp the string to remove the trailing newline before finding the length.

    the order is not sorted although i have used to sort function for that.

    By default, sort sorts in lexicographical order, so 100 comes before 90 because 1 comes before 9. To sort numerically, do this:

    my @array = sort { $a <=> $b } $frstLength, $scndLength, $trdLength, $ +frthLength;

    You should also begin your script with use strict;, which forces you to declare each variable with my. (This is a good thing! It will save you a lot of debugging time in the long run.)

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hello Athanasius Thank you for your explanation it helped but can you please explain what does this code { $a <=> $b } means?

        Athanasius uses the sort BLOCK LIST syntax of sort. The block is {$a <=> $b}. Blocks are documented in Basic BLOCKS. The operator (<=>) is described in Equality Operators. The package variables $a and $b are described through out the documentation for sort. The short answer is that this block tells sort to sort the list in numerical order rather than the default lexical order.
        Bill
Re: Length of strings in an array
by NetWallah (Canon) on Sep 20, 2020 at 18:02 UTC
    Here is a more "perl-ish" way to do this, using a perl "array" (@seq).

    "push" adds stuff into the back of an array, while "pop" removes it.
    "chomp" deletes the last "line ending" character(s), if they exist.
    The "sort" uses the "Numeric compare" operator "<=>" to compare the length, and returns each item in the sorted array as "$_", which is then printed along with a newline (\n).
    The sort BLOCK using "$a <=> $b" is a common/canonical perl idiom for numeric sort. Just accept that till you research it deeper. "$_" is commonly used as a "temporary" variable when the programmer is too lazy to give it a name.

    use strict; use warnings; my @seq; # DNA sequence strings do{ print "Please enter DNA sequence (END to finish):"; push @seq , $_=<STDIN>; # First, assign whatever is read into $_, + then append it to @seq } until $_ eq "END\n"; pop @seq; # Remove the extra "END\n" entry; chomp @seq; # Remove line endings on each entry print "$_\n" for sort {length $a <=> length $b} @seq;
    Note - this code is not limited to 4 entries - it requires an END to be entered after the last entry.

                    "Imaginary friends are a sign of a mental disorder if they cause distress, including antisocial behavior. Religion frequently meets that description"

Re: Length of strings in an array
by GrandFather (Saint) on Sep 20, 2020 at 21:31 UTC

    If you really want a fixed number of entries then this variation of NewWalla's reply may help.

    use strict; use warnings; my @seq; # DNA sequence strings for my $count (1 .. 4) { print "Please enter DNA sequence $count:"; push @seq, scalar <STDIN>; } chomp @seq; # Remove line endings on all entries printf "%2d: %s\n", length $_, $_ for sort {length $a <=> length $b} +@seq;

    Prints (for some arbitrary input):

    Please enter DNA sequence 1:asdf Please enter DNA sequence 2:zvasdfasf Please enter DNA sequence 3:asd Please enter DNA sequence 4:asdfasg 3: asd 4: asdf 7: asdfasg 9: zvasdfasf

    You can visit PerlDoc to find out what scalar does.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re: Length of strings in an array
by AnomalousMonk (Archbishop) on Sep 21, 2020 at 03:20 UTC

    Here's another approach. In addition to collecting user input, it tries to control (the user can exit the collection loop early using loop control) and validate (using regexes or regular expressions — see perlre, perlretut, perlreref and perlrequick for info on these) the input. Any upper- or lower-case alpha character is accepted as a "DNA" character, but you can alter the validation regex to refine this for your application. It also has some debug statements; take them out for final use. :)

    Script: get_seqs_1.pl:

    Output:
    Win8 Strawberry 5.8.9.5 (32) Sun 09/20/2020 22:47:03 C:\@Work\Perl\monks\shabird >perl get_seqs_1.pl please enter DNA sequences: first sequence: dddddd secundus sequence: sss third sequence: ffffffffff 4th sequence: gggggg $VAR1 = { 'first' => { 'len' => 6, 'seq' => 'dddddd' }, 'secundus' => { 'len' => 3, 'seq' => 'sss' }, '4th' => { 'len' => 6, 'seq' => 'gggggg' }, 'third' => { 'len' => 10, 'seq' => 'ffffffffff' } }; valid entered sequences in order of prompt: first: dddddd (6) secundus: sss (3) third: ffffffffff (10) 4th: gggggg (6) valid entered sequences in order of increasing length: secundus: sss (3) first: dddddd (6) 4th: gggggg (6) third: ffffffffff (10)


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11121963]
Approved by Athanasius
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2024-04-25 11:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found