Home

Mutators

  • Nov. 8th, 2007 at 2:06 PM
obscure
Let us consider the following code to loop over the keys from a dictionary in Python:

  for key in a_dict.keys():
This would be nearly the same in Perl:

  for my $key in (keys %a_dict) {
And Perl 6*:

  for %a_dict.k -> my $key {
But now you say: I want to have in a sorted rather then arbitrary order!

In Python you have to allocate a temporary variable, sort it, then loop over the result:

  the_keys = a_dict.keys()
  the_keys.sort()
  for key in the_keys:
Where as Perl takes a functional approach that is, in my opinion, a lot clearer:

  for my $key in (sort keys %a_dict) {
And Perl 6*:

  for sort %a_dict.k -> my $key {
* I vaguely recall something about the temporary variables used in loops not requiring an explicit "my" but I can't seem to find something saying that explicitly now.

[Edit] So as many people pointed out to me, this was fixed for Python as of 2.4 (my laptop and work machines all use 2.3) with: for key in sorted(a_dict.keys()): What's more, the .keys() is assumed so you can actually just do for key in a_dict: or for key in sorted(a_dict):

Latest Month

January 2008
S M T W T F S
  12345
6789101112
13141516171819
20212223242526
2728293031  

Tags

Page Summary

Syndicate

RSS Atom
Powered by LiveJournal.com