0

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;

2 Answers 2

4

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];
Sign up to request clarification or add additional context in comments.

2 Comments

My input is 1 or 2 or 0 or mon however error message popups unrecognized day... What is actual input?
Either check if you have a number, or add the number to the map. I did the latter.
-1

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

$

2 Comments

this is working for (Mon, Tue,Wed) only but not for other days.
it works.. please check case sensitivity as stored in the hash..and any extra spaces

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.