Yarok
Yarok

Reputation: 123

initialise a hash's keys with an array

I need to initialize a hash of hashes. The way I do it is below, is there a more elegant way to do it?

$biggest_word_size = 0;
foreach $sig (@signals) 
    {
    $sigs->{$sig} = "None";
    $biggest_word_size = 
        ( $biggest_word_size > length($sig) ) ? $biggest_word_size : length($sig) ;
    }

Upvotes: 1

Views: 197

Answers (4)

Darren Westall
Darren Westall

Reputation: 226

@signals = sort{ length($a) <=> length($b) } @signals;
my $sigs = { map { $_ => 'None' } @signals };
my $biggest_word_size = length($signals[-1]);

I would use a sort to achieve this.

Upvotes: 0

esskar
esskar

Reputation: 10970

use List::Util qw[max];
my $biggest_word_size = 0;
my $sigs = { map { 
    $biggest_word_size = max($biggest_word_size, length $_);
    $_ => 'None' } @signals };

Upvotes: 2

DVK
DVK

Reputation: 129509

  1. To be honest, for what you want, this is pretty much as elegant as you want. You can do it in a slightly more idiomatic way, but why? It's perfectly readable and concise enough

  2. If the size of your array is not too large, and you don't care about squeezing every last ounce of performane, you can do those 2 tasks separately in a slightly more idiomatic way (at the cost of scanning the array twice):

     use List::Util qw(max);
     my $sigs = { map {$_ => 'None'} @signals };
     my $biggest_word_size = max map {length} @signals;
    

Upvotes: 4

Sodved
Sodved

Reputation: 8608

Well, if you ignore the $biggest_word_size bit, to initialise a hashref from an array can be

my $sigs = { map { $_ => 'None' } @signals };

Upvotes: 1

Related Questions