manbroski has asked for the wisdom of the Perl Monks concerning the following question:
Greetings, Monks.
In my weary travels, I have found a serene beauty in your language. It is sometimes harsh, but it is also beautiful. I come from the land of Python, were folks carry their language as a hammer, always clear and to the point. However, at times I wish that I can wield a rapier, swift and effective. Which is why I come to the Monastery.
Recently, I have started looking at problems on Rosalind (rosalind.org) and decided to solve all the tasks in Perl. Question number 1 is particularly interesting. It is simple, yet writing clean code for it may be a challenge. The task is simple - count letters in a string and print counts in alphabetical order.
Here is what I came up with
#!/usr/bin/env perl #Question 1: Counting DNA nucleotides use v5.16; sub sort_and_print_hash_keys (\%) { my %hash = %{shift()}; foreach (sort keys %hash) { print "$hash{$_} "; } print "\n"; } sub counting { my %letters = (); chomp(my $seq = readline); foreach my $base (split //, $seq) { $letters{$base}++; } sort_and_print_hash_keys(%letters); } counting();
As you might see, I like clean and meaningful code. One thought per line.
My question is twofold. First, is this idiomatic Perl? Would you have done something differently? Please, critique this.
Second, I am wondering if the magic behind hash ref passing has any side effects. Here, I use a subroutine prototype declaration to ensure argument type safety and dereference immediately with %{shift()}. Are there any undesired consequences of this? Does any other code flatten out data structures or makes unnecessary copies? I am aware that 'sort keys' would create a separate array of keys.
Thank you, monks. I eagerly await your wisdom
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Entering the land of Perl
by choroba (Cardinal) on Apr 04, 2013 at 21:38 UTC | |
by manbroski (Initiate) on Apr 04, 2013 at 21:51 UTC | |
by choroba (Cardinal) on Apr 05, 2013 at 06:06 UTC | |
|
Re: Entering the land of Perl
by jwkrahn (Abbot) on Apr 04, 2013 at 23:30 UTC | |
by manbroski (Initiate) on Apr 04, 2013 at 23:52 UTC | |
by 2teez (Vicar) on Apr 05, 2013 at 03:17 UTC | |
by jwkrahn (Abbot) on Apr 05, 2013 at 14:37 UTC | |
|
Re: Entering the land of Perl
by Discipulus (Canon) on Apr 05, 2013 at 07:42 UTC | |
|
Re: Entering the land of Perl
by hdb (Monsignor) on Apr 05, 2013 at 10:18 UTC | |
|
Re: Entering the land of Perl
by Cristoforo (Curate) on Apr 24, 2013 at 22:18 UTC |