adamcrussell

Perl Weekly Challenge 034

Time constraints prevented me from really rolling my sleeves up and exploring different aspects of this week's Perl Weekly Challenge. Somewhat conveniently both parts yielded short solutions, although both have intriguing aspects which will have to be left for another time!

Part 1

Sample Run

$ perl perl5/ch-1.pl
second
fourth

Notes

I think maybe the most significant issue with hash slices in Perl is that you need to switch the sigil on the hash top be @. If you do not and, for example, leave it as a %, then you will receive both the keys and the matching values.

Part 2

Sample Run

$ perl perl5/ch-2.pl
Hello!
Goodbye!

Notes

  • A dispatch table is really just an arrangement of references to functions. It isn't strictly required that they even be in a hash.
  • You don't have to have anonymous functions, I just did it this way for the sake of brevity. You could declare functions the normal way and then use references to them. 
  • Make sure that, in the case of using a hash as I did, to not just retrieve the functions from the hash but actually make sure perl knows to execute them. If I did not add have, for example, $dispatch_table{hello}() but instead just had $dispatch_table{hello} I would have gotten this error:

    Useless use of hash element in void context at perl5/ch-2.pl line 10.

Comments for this post were locked by the author