Perl从用户获取输入并确定数组值

时间:2018-04-24 10:14:19

标签: perl

有些背景,我应该创建一个perl脚本来获取用户输入的值,包括1到7。

当用户输入1时,应该打印星期日。小杯茶。

当用户输入2时,应该在星期一打印。大杯咖啡等。

我可以达到最终结果,但是我实现它的方式不正确,因为我将$ number值减少1以便访问数组第一个元素

正确的方法是当用户输入1而不将值减1时,它应该能够知道它是引用数组中的第一个元素。

希望有人可以就此发表一些看法。

        my @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

        my %beverages = ('Sunday' => tea, 'Monday' => coffee, 'Tuesday' => tea, 'Wednesday' => coffee, 'Thursday' => tea, 'Friday' => coffee, 'Saturday' => tea );

        print "Please enter a number between 1 and 7 (inclusive) \n";
        my $number = <STDIN>;
        $number -=1;
        $which = $days[$number];
        $mod = ($number+1) % 2;


        if ($days[$number] == $name[$number])
        {
            print "$days[$number].";
            if ($mod == 0)
            {
            print "Large cup of $beverages{$which}";
            }
            else
            {
            print "Small cup of $beverages{$which}";
            }
        }

1 个答案:

答案 0 :(得分:2)

我不理解您的测试if ($days[$number] == $name[$number]),因为没有@name这样的数组,所以我完全删除了

这似乎符合您的要求。我选择计算饮料,因为它以与尺寸相同的方式交替。您必须始终 use strictuse warnings 'all'并在首次使用时使用my声明所有变量

use strict;
use warnings 'all';

my @days = qw/
    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
/;
my @beverages = qw/ coffee tea /;
my @sizes     = qw/ Large Small /;

print "Please enter a number between 1 and 7 (inclusive): ";
chomp( my $number = <STDIN> );

my $dayname = $days[$number-1];
my $drink   = $beverages[$number % 2];
my $size    = $sizes[$number % 2];

print "$dayname. $size cup of $drink\n"