Perl: can I skip the hash intermediate variable in this case?

I am currently using something like this:

my %tmpHash = routineReturningHash();
my $value = $tmpHash{'someKey'};

The only thing I need is $value, I do not need %tmpHash. Therefore, I am interested to know if there is a way to avoid the announcement %tmpHash.

I tried

my $value = ${routineReturningHash()}{'someKey'};

but it does not work and displays a strange error: " Can't use string ("1/256") as a HASH ref while "strict refs" in use".

Any ideas on how to do this?

+4
source share
1 answer

Create a hashref from the returned list, which you can then dereference

my $value = { routineReturningHash() }->{somekey};

In what you tried, ${ ... }inserts a scalar context inside. From perlref (my emphasis)

2. , ( ) , , .

; hashref.


, . , , hashref sub.

: , ( ), ; , .

... , , , , .

,

  • , return \%hash;

  • hashref return { key => 'value', ... };

  • ,

    sub work_by_ref {    
        my ($hr) = @_;
        $hr->{key} = 'value';
        return 1;
    }
    
    my %hash;
    work_by_ref(\%hash);
    say "$_ => $hash{$_}" for sort keys %hash;
    

    C; Perl , . sub, return \%hash;

+9

Source: https://habr.com/ru/post/1689168/


All Articles