Perl equivalent of Python for loop?

Issue

Is there a Perl equivalent to the following Python code?

names['name'] = ['Bob', 'Bill', 'Terry']
obj = {'Students': [ {'Names': name} for name in names['name']]}

This’ll end up looking like something like this

EDIT:
As Tim Roberts pointed out: The result would look like this

[ {'Names': "Bob" }, { "Names": "Bill" },. { "Names": "Terry" } ]

I’ve seen Perl one liners that do different things, but not this.

Solution

You want a map inside of your data structure. It’s not a one-liner. It’s just normal code.

my $obj = {
  'Students' => [
    map { 'Names' => $_ }, @{ $names{name} }
  ]
};

I have used the expression form map (map EXPR, LIST) with a comma (,) after the expression that is being evaluated. The curly braces ({}) are the hash reference constructor. Alternatively, you could use the block form (map BLOCK LIST), which would have an extra pair of curlies.

    map { { 'Names' => $_  } } @{ $names{name} }

If you want a plain hash rather than a reference, substitute like this.

my %obj = (
# ...
);

Answered By – simbabque

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published