简体   繁体   中英

how can i Create indexed variable in perl?

I am new to perl, how can i create indexed variable like $Num0, $Num1 and $value0, $value1. I have to store some value from hash in this variable.

 $Num0 = $req->{value0};
 $Num1 = $req->{value1};
 $Num2 = $req->{value2};

is it possible to crate both variable Num0,Num1 and value0,value1 using some logic based on indexing like below.

while($i < 5)
{
 $Num.$i = $req->{value$i};
}

You can use perl arrays.

my @num;
my $i=0;
while ($i<5) {
    $num[$i] = $req->{"value$i"};
    $i++;
}

See perl cheatsheet for concise help on perl.

@ikegami suggested some alternative ways to do the same thing in comments:

my @num = map { $ref->{"index$_"} } (0..4);

and

my @num;
for my $i (0..4) {
    push @num, $ref->{"index$i"};
}

See help on map and push .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM