1. Perl
  2. Operators
  3. here

Hash slice

You can retrieve multiple values from hash using a feature called hash slice .

my @math_score_slice = @math_scores{'Aiko', 'Kenta'};

Hash slices allow you to specify multiple keys and retrieve the values as a list. Note that the prefix is @, not $ or %, and the keys is surroundded by {}.

For hash reference, you can do a hash slice like this:

my @math_score_slice = @$math_scores{'Aiko', 'Kenta'};

Use hash slice as lvalue

@math_score_of{'Aiko', 'Kenta'} = (20, 40);

You can assign a hash slice to the corresponding key by using it as an lvalue.

Array slice

A similar feature to hash slice is array slice. Array slices can be used to retrieve multiple elements of an array.

# Array slice
my @values = @array[0, 3, 5];

Example program

This is an example program for hash slice.

use strict;
use warnings;
use Data::Dumper;

# Student math scores
my %math_scores = (
  Aiko => 89,
  Kenta => 100,
  Taro => 34,
);

print "original hash\n";
print Dumper \%math_scores;
print "\n\n";

# 1: Hash slice
print "1: Hash slice (get values for Aiko and Kenta)\n";
my @math_score_slice = @math_scores{'Aiko', 'Kenta'};
print "\@math_score_slice =", join(',', @math_score_slice), ")\n\n";

# 2: Use hash slice as lvalue (set values for Aiko and Kenta)
print "2: Use hash slice as lvalue"
  . "(Set values for Aiko and Kenta)\n";
@math_scores{'Aiko', 'Kenta'} = (20, 40);
print Dumper \%math_scores;

Output:

original hash
$VAR1 = {
          'Kenta' => 100,
          'Aiko' => 89,
          'Taro' => 34
        };


1: Hash slice (get values for Aiko and Kenta)
@math_score_slice =89,100)

2: Use hash slice as lvalue(Set values for Aiko and Kenta)
$VAR1 = {
          'Kenta' => 40,
          'Aiko' => 20,
          'Taro' => 34
        };

Reference: join function

Related Informatrion