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
In reply to Entering the land of Perl by manbroski
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |