Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: One-liner to join keys on a two-dimensionnal hash ?

by ikegami (Patriarch)
on Dec 29, 2021 at 14:44 UTC ( [id://11140006]=note: print w/replies, xml ) Need Help??


in reply to One-liner to join keys on a two-dimensionnal hash ?

Close.

my $expr = join '|', map { keys( %{ $replaces{$_} } ) } keys( %replaces );

With foreach:

my @keys; for ( keys( %replaces ) ) { push @keys, keys( %{ $replaces{$_} } ); } my $expr = join '|', @keys;

Replies are listed 'Best First'.
Re^2: One-liner to join keys on a two-dimensionnal hash ?
by Anonymous Monk on Dec 29, 2021 at 15:01 UTC
    OP here!
    Thanks a lot for your help, I didn't know that map could be used such a way (i.e. having an output instead of altering every item in a list)..
    Have a greet day!

      That the point of map. It takes a list of inputs, and produces a different list from those inputs. It does so by applying the transformation function (the block or expression) to each input, and collecting the outputs of that function.

      Examples:

      my @uc = ( uc("abc"), uc("def") ); | v my @uc = map { uc($_) } "abc", "def";
      my %h = ( "abc" => 1, "def" => 1 ); | v my %h = map { $_ => 1 } "abc", "def";

      I didn't know that map could be used such a way (i.e. having an output instead of altering every item in a list)

      Erm, that is what map is for! :) Perl::Critic even provides a ProhibitVoidMap policy to warn you of code that uses map in void context.

      I suggest you follow the simple stylistic advice given in Effective Perl Programming in the item "Use foreach, map and grep as appropriate" namely:

      • Use foreach to iterate read-only over each element of a list
      • Use map to create a list based on the contents of another list
      • Use foreach to modify elements of a list
      • Use grep to select elements in a list

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140006]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-20 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found