Perl: Define a hash with reference to the same hash, $ this & # 8594; {key}?

How to create a hash as shown below:

my %hash = (key1=>"Something", key2=>$hash{key1} . "Else");

Could this not be done when I declare a hash? So far, the only thing I've come up with has been:

my %hash = (key1=>"Something");
$hash{key2} = $hash{key1} . "Else";
+5
source share
7 answers

Why not use an intermediate variable?

my $common_value = 'Something';
my %some_hash = ( k1 => $common_value, k2 => $common_value.'Else' );

Update

kemp asked why an intermediate variable was needed. I can interpret this question in two ways, I will try to answer both interpretations.

  • Why can't you do my %hash = ( k1 => 'foo', k2 => $hash{k1}.'bar' );?

    (rhs) (lhs). , k2 , %hash. , %hash . (%hash , .)

  • , ?

    , . , .

    my $cv1 = sub_result() * 5;
    my $cv2 = "Number: $cv1";
    
    my %h = (
        k1 => $cv1,  
        k2 => $cv2,
        k3 => "Numero: $cv1",
        k4 => "Big $cv2",
        k5 => "Round $cv2",
        k6 => "Whole $cv2",
        k7 => "-$cv1",
    );
    

    , , , , , , , . , , :

    use Scalar::Util qw(reftype);
    
    my @init = ( 
        [ key1 => $value                 ],
        [ key2 => \&make_a_value, 'key1' ],
        [ key3 => \&another_way,  'key2' ],
    );
    
    my %h; 
    for my $spec ( @init ) {
        my $key   = shift @$spec;
        my $value = shift @$spec;
        my @args  = @$spec;
    
        if( reftype $value eq reftype sub {} ) {
            $value = $value->( @h{ @args } );
        }
    
        $h{$key} = $value;
    }
    

    , , , , , . , . - . , .

+11

:

  • , Perl key2 => $hash{key1}, , 1, - . , $hash{key1} , key2 => $hash{key1}.

  • : %hash key2 => $hash{key1} (- /), barf, use strict;, . my %hash , # 1 - .

+9

, , $hash {key1} , . 1 , .

+4

my %hash = ( key1 => "Something", key2 => "Something" . "Else" );

?

, , , , , , ( ), ?

+1

-, . . // , perl - , :

.

package Class;
use Moose;
has [qw/key1 key2/] => ( isa => 'Str', is => 'rw', init_arg => 'key1' );

my $o = Class->new( { key1 => 'foobar' } );
print $o->key1, $o->key2;
0
source

You can get close enough, but I'm not sure if it has a value other than novelty:

$_->{key2} = $_->{key1} . "Else" for my $hash = { key1 => "Something" };
0
source

If the creation of an intermediate variable outside the hash function is not performed, then using it do blockcan make it more aesthetic:

my %hash = (
    do {
        my $s = 'Something';
        ( key1 => $s, key2 => $s . 'Else' );
    },
);

/ I3az /

0
source

All Articles