Andrey (azangru) wrote,
Andrey
azangru

Have to learn Perl, and am finding it frustratingly elusive. Especially in dealing with variables. That there is a keyword for declaring a variable ("my"; I haven’t yet got to a point where I would need "our") is understandable, although Ruby and Python manage to do without; but the differences between $, @, and % are making me cry. I was trying for half an hour to make this function, for looping through an array of hashes (that comes from a decoded JSON) work:

sub render_children {
  my @children_data = @_[0];

  foreach my $term (@children_data) {
    say ref($term);
    say Dumper $term;
  }
}


The children_data passed to the function were an array (of hashes); I was pretty sure about that. So, does this mean they are @children_data? Or $children_data that will be a reference to the children_data array? Or will $children_data be in fact the scalar representation of the array, i.e. its length? It’s thousand times worse that JavaScript’s "this", honestly!

Anyway, the foreach loop in the function above was not working the way I expected. Instead of individual hashes from that array, what I was seeing in the console bound to the $term variable was the original array. How can one foreach an array and get this very array passed as an element into the loop is completely beyond me. Finally, inspired by a discussion on StackOverflow, I changed the code to this:

sub render_children {
  my $children_data = @_[0];

  foreach my $term (@{$children_data}) {
    say ref($term);
    say Dumper $term;
  }
}


Now the function works as I intended — it loops through the hashes in the array. But what the hell does it mean? What is $children_data? Why should it be a scalar? What, in turn, is "@{$children_data}"? What sick mind came up with such lunacy as this? Why do I need to annotate variables this way in a dynamically typed language? There is nothing even remotely that insane in JavaScript, or Python, or Ruby, or PHP. Not even in Haskell. Not that I can write Haskell, but still.
Subscribe

  • (no subject)

    Someone is actually running a youtube ad campaign targeting React developers with a course on becoming a UI architect: The site that the ad…

  • (no subject)

    A beautiful cartoon on the front page of The Week:

  • (no subject)

    This is just as bad as a brief exchange with a belligerent guest on a regular news show: Six minutes! Six minutes, during which Rand Paul is…

  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments