Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 474
Mimosinnet Avatar asked May 04 '18 14:05

Mimosinnet


1 Answers

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;
}
like image 177
Jonathan Worthington Avatar answered Nov 15 '22 09:11

Jonathan Worthington