使用哈希在Perl中编写程序

时间:2018-11-21 03:24:33

标签: perl

我想在得到用户输入后两天打印出来。

示例:

enter a day :
Input : Wednesday

Output : monday

我使用数组哈希对它进行了尝试,但找不到结果。

%hash=('mon',1,'tue',2,'wed',3);
@arr=keys %hash;

2 个答案:

答案 0 :(得分:4)

您的尝试是倒退。您要搜索的字符串应该是哈希键。

my @days = qw( mon tue wed );
my %index_of_day = map { $days[$_] => $_, $_ => $_ } 0..$#days;

defined( my $input = <> )
   or die("Premature EOF\n");

chomp($input);

my $old_index_of_day = $index_of_day{$input}
   or die("Unrecognized day $input\n");

my $new_index_of_day = $old_index_of_day - 2;
$new_index_of_day += @days while $new_index_of_day < 0;

my $output = $days[$new_index_of_day];

答案 1 :(得分:-1)

使用交互式perl-one衬纸。请注意,它区分大小写,并且如果与%hash的键不匹配,则不会打印任何内容。

$ perl -ne 'BEGIN{printf("%s","Enter the input: "); my $inp=<STDIN>; chomp($inp); %hash=('Mon',1,'Tue',2,'Wed',3,'Thu',4,'Fri',5,'Sat',6,'Sun',7); $x=$hash{$inp}-2; $x
+=7 if $x<1; exit if not exists $hash{$inp}; foreach my $y (keys %hash) { print "$y" if $hash{$y}==$x } ; exit } '
Enter the input: fff


$ perl -ne 'BEGIN{printf("%s","Enter the input: "); my $inp=<STDIN>; chomp($inp); %hash=('Mon',1,'Tue',2,'Wed',3,'Thu',4,'Fri',5,'Sat',6,'Sun',7); $x=$hash{$inp}-2; $x
+=7 if $x<1; exit if not exists $hash{$inp}; foreach my $y (keys %hash) { print "$y" if $hash{$y}==$x } ; exit } '
Enter the input: Mon
Sat

$ perl -ne 'BEGIN{printf("%s","Enter the input: "); my $inp=<STDIN>; chomp($inp); %hash=('Mon',1,'Tue',2,'Wed',3,'Thu',4,'Fri',5,'Sat',6,'Sun',7); $x=$hash{$inp}-2; $x
+=7 if $x<1; exit if not exists $hash{$inp}; foreach my $y (keys %hash) { print "$y" if $hash{$y}==$x } ; exit } '
Enter the input: Tue
Sun

$