Mimosinnet
Mimosinnet

Reputation: 875

perl6: access values in a multidimensional variable

Perl6 Twitter module gives a multidimensional variable with the tweets from a search query. This code:

%tweets<statuses>[0]<metadata><iso_language_code>.say;
%tweets<statuses>[0]<created_at>.say;

prints:

es
Fri May 04 13:54:47 +0000 2018

The following code prints the 'created_at' value of the tweets from the search query.

for @(%tweets<statuses>) -> $tweet {
  $tweet<created_at>.say;
}

Is there a better syntax to access the values of the variable %tweets?

Thanks!

Upvotes: 5

Views: 120

Answers (1)

Jonathan Worthington
Jonathan Worthington

Reputation: 29454

If the question is whether there is a shorter syntax for hash indexing with literal keys than <...>, then no, that's as short as it gets. In Perl 6, there's no conflation of the hash data structure with object methods/attributes/properties (unlike with JavaScript, for example, where there is no such distinction, so . is used for both).

There are plenty of ways to get rid of repetition and boilerplate, however. For example:

%tweets<statuses>[0]<metadata><iso_language_code>.say;
%tweets<statuses>[0]<created_at>.say;

Could be written instead as:

given %tweets<statuses>[0] {
    .<metadata><iso_language_code>.say;
    .<created_at>.say;
}

This is using the topic variable $_. For short, simple, loops, that can also be used, like this:

for @(%tweets<statuses>) {
    .<created_at>.say;
}

Upvotes: 8

Related Questions