gpt4 book ai didi

perl - 如何按照添加元素的相同顺序打印散列?

转载 作者:行者123 更新时间:2023-12-02 07:37:22 25 4
gpt4 key购买 nike

是否可以以 LIFO 或 FIFO 方式使用哈希?我如何确保散列以与添加元素相同的顺序打印?

#!/usr/bin/perl

print "content-type: text/html \n\n";

# BEGINNING HASH
%coins = ( "Quarter" , .25,
"Dime" , .10,
"Nickel", .05 );
# PRINT THE OLD HASH
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
}

# ADD NEW ELEMENT PAIRS
$coins{Penny} = .01;
$coins{HalfDollar} = .50;

# PRINT THE NEW HASH
print "<br />";
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
}

这给出了

Nickel, 0.05Dime, 0.1Quarter, 0.25Nickel, 0.05Dime, 0.1HalfDollar, 0.5Penny, 0.01Quarter, 0.25

最佳答案

你可以保留一个单独的散列键数组,这样你就可以写

my @coins = qw/ Quarter Dime Nickel Penny HalfDollar /;

for my $key (@coins) {
print "$key, $coins{$key}<br />\n";
}

或者您可以安装和使用 Tie::IxHash模块,它将按照插入的顺序保留哈希元素,就像这样

use strict;
use warnings;

use Tie::IxHash;
tie my %coins, 'Tie::IxHash';

print "content-type: text/html \n\n";

%coins = (
Quarter => 0.25,
Dime => 0.10,
Nickel => 0.05,
);

while (my ($key, $value) = each %coins){
print "$key, $value<br />\n";
}

$coins{Penny} = .01;
$coins{HalfDollar} = .50;

print "<br />\n";
while (my ($key, $value) = each(%coins)){
print "$key, $value<br />\n";
}

关于perl - 如何按照添加元素的相同顺序打印散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14954816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com