Reputation: 59
I want to print 2 days back after getting input from user.
Example:
enter a day :
Input : Wednesday
Output : monday
I tried it using hashing with array but can't find result.
%hash=('mon',1,'tue',2,'wed',3);
@arr=keys %hash;
Upvotes: 0
Views: 88
Reputation: 386706
Your attempt is backwards. The strings by which you want to search should be the keys of the hash.
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];
Upvotes: 4
Reputation: 8811
Using interactive perl-one liner. Note that it is case sensitive and doesn't print anything if it is not matching the keys of the %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
$
Upvotes: -1