'How to directly assign the SOLE hash key to a scalar in perl
Is it possible to assign the only existing hash key directly to a scalar?
For example can these two statements be combined into one?
@the_keys = keys %the_hash; # a hash with a single key
$the_sole_key = shift @the_keys;
The existence of a single key in %the_hash
has been verified in preceding code.
Solution 1:[1]
my ($key) = keys(%hash);
or
my $key = ( keys(%hash) )[0];
Solution 2:[2]
Two additional one-liners. Is there an argument for preferring one of these solutions over the others? For instance, do any of these solutions take less time or use fewer computing resources?
#!/usr/bin/env perl
use strict; use warnings;
use Data::Dumper qw(Dumper); $Data::Dumper::Sortkeys = 1;
use feature 'say';
my%stuff=('06'=>'fly',);
print Dumper\%stuff;
my $what;
say 'extract from anonymous array :';
$what=[keys%stuff]->[0];say$what;
say 'join list:';
$what=join '',keys%stuff; say$what;
say 'remove parentheses from earlier-posted solution :';
($what)=keys%stuff; say$what;
say 'remove parentheses from 2nd earlier-posted solution :';
$what=(keys%stuff)[0];say$what;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ikegami |
Solution 2 |