Написать программу на Perl, используя хэш - PullRequest
0 голосов
/ 21 ноября 2018

Я хочу напечатать 2 дня назад после получения ввода от пользователя.

Пример:

enter a day :
Input : Wednesday

Output : monday

Я пробовал использовать хеширование с массивом, но не могу найти результат.

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

Ответы [ 2 ]

0 голосов
/ 21 ноября 2018

Ваша попытка обратная.Строки, по которым вы хотите искать, должны быть ключами хеша.

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];
0 голосов
/ 21 ноября 2018

Использование интерактивного лайнера perl-one.Обратите внимание, что он чувствителен к регистру и ничего не печатает, если он не совпадает с ключами% хеша.

$ 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

$
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...