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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.