Vicky
Vicky

Reputation: 1338

Hash assignment as array

I'm trying to understand the piece of code below; I just cannot understand what is being done in line 15.

It seems like it is trying to initialise/assign to %heading but I am just not sure how that syntax works.

$strings = [qw(city state country language code   )];

my $file = "fname";
my $fn   = $strings;
my $c    = 0;

open( FILEH, "< ${file}.txt" ) or die( $! );

while ( <FILEH> ) {

    my %heading;
    chomp;
    $c++;

    @heading{ ( @$fn, "One" ) } = split( /[|]/ );  # Line 15

    if ( defined( $heading{"One"} ) ) {
        my $One = $heading{"One"};
    }

Upvotes: 1

Views: 103

Answers (1)

choroba
choroba

Reputation: 242218

That's called a "slice". It assigns to several keys at once:

@hash{ $key1, $key2 } = ($value1, $value2);

is a shorter and faster way of doing

$hash{$key1} = $value1;
$hash{$key2} = $value2;

@$fn is the same as @{ $fn }, i.e. array dereference.

Upvotes: 6

Related Questions