Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a only part of a hash in Perl?

Tags:

Is there a way to get a sub-hash? Do I need to use a hash slice?

For example:

%hash = ( a => 1, b => 2, c => 3 ); 

I want only

%hash = ( a => 1, b => 2 ); 
like image 628
Timmy Avatar asked Jun 11 '09 03:06

Timmy


People also ask

How do you access the elements of a hash in Perl?

Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

How do I get the first element of a hash in Perl?

my %h = ( secret => 1; );

How do I print a hash element in Perl?

print "$ perl_print_hash_variable{'-hash_key2'} \n"; Description: The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.

What is %$ in Perl?

It means a scalar value, as in $hash{key} and $array[$num]. In this case it's a scalar variable because it's a scalar value and there is no indexing chars after it.


1 Answers

Hash slices return the values associated with a list of keys. To get a hash slice you change the sigil to @ and provide a list of keys (in this case "a" and "b"):

my @items = @hash{"a", "b"}; 

Often you can use a quote word operator to produce the list:

my @items = @hash{qw/a b/}; 

You can also assign to a hash slice, so if you want a new hash that contains a subset of another hash you can say

my %new_hash; @new_hash{qw/a b/} = @hash{qw/a b/}; 

Many people will use a map instead of hash slices:

my %new_hash = map { $_ => $hash{$_} } qw/a b/; 

Starting with Perl 5.20.0, you can get the keys and the values in one step if you use the % sigil instead of the @ sigil:

my %new_hash = %hash{qw/a b/}; 
like image 152
Chas. Owens Avatar answered Sep 30 '22 06:09

Chas. Owens