I have a variable which I want to take the first capture and use that as the key for a hash. I found a solution but it seems suboptimal.
My $out = $hash{[$var =~ /(^[a-z]+)/]->[0]};
It's seems like there has to be a better way then going list->array->scalar. Maybe just list->scalar. I know that I could also capture in another variable and then use that as a key, but I want to avoid that. Is there a better way to do this?
无需创建数组引用。
my $out = $hash{ ($var =~ m/(^[a-z]+)/)[0] };
There's no need to cram everything into a single statement
my ($key) = $var =~ /(^[a-z]+)/;
my $out = $hash{ $key };
but something like this would be okay
my $out;
$out = $hash{$1} if $var =~ /(^[a-z]+)/;
or possibly
my $out = $var =~ /(^[a-z]+)/ && $hash{$1};
What´s wrong with?
$var =~ /^([a-z]+)/;
my $out = $hash{$1};
It is useful to use the output of =~
in list context for more than one match, but for a single one?
If you are expecting the regex to not match (as suggested by other people), it will be better to check first. For instance:
if( $var =~ /^([a-z]+)/ ) {
my $out = $hash{$1};
...
}
If you want a one-liner, you may use:
my $out = $hash{ ($var =~ /^([a-z]+)/)[0] };
This will give a warning if the regex does not match. It was suggested first by @tinita.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.