在Perl中编写Ruby脚本

时间:2015-11-09 13:20:33

标签: perl

我正在用三种不同的语言编写一个简单的脚本,Python,Ruby和Perl。我对Perl非常陌生,但我真的很想学习它。我的问题是,我不知道如何在Perl中编写一个方法,就像在Ruby中一样。我很确定一个方法在Perl中被称为函数,但我不确定..

以下是我用三种语言写的内容: Ruby(我到目前为止)

=begin 
Test program to choose language
Ruby
creator Me
=end

def welcome
    choices = %w(Perl Python Ruby)
    lang = 3
    puts "Welcome, to the test script, this will test what language you would like to learn.. In order to find out these choices, write this same definition in all three different languages"
    puts "There are", lang, "languages to choose from please choose one:"
    print choices
    print ">\t"
    input = gets.chomp
    if input =~ /perl/i
        puts "You have chosen Perl!"
    elsif input =~ /python/i
        puts "You have chosen Python!"
    else
        puts "You're already writing in Ruby!! Let me choose for you:"
        print "#{choices.sample}\n"
    end
end
welcome

正如您所看到的,这是一个非常简单的脚本,我觉得好像用三种不同的语言编写它会帮助我选择下一个我想学习的东西(我已经知道Ruby)。

有人可以向我解释如何在Perl中编写方法吗?我用谷歌搜索了它,但我似乎无法使用“Perl中的方法”获得任何好处。非常感谢您提前感谢。

3 个答案:

答案 0 :(得分:3)

你似乎没有在该代码中做任何事情,所以一种方法似乎有点矫枉过正。使用简单的subroutine会更常见。

sub welcome {
    ...
}
welcome();

如果你真的想使用某种方法,那么perlootut就是经典方法。这些天很多人使用Moose编写OO代码。

它仍然归结为编写一个sub,只是一个位于包定义的中间而不是简单的脚本。

答案 1 :(得分:1)

使用perl,变量有“sigils”来确定它们的“类型”:

my $scalar = "a scalar value";
my @array = ('a', 'list', 'of', 'scalar', 'values');
my %hash = (key1 => "value1", key2 => "value2");

请参阅perldoc perldata

从perl版本5.10开始,有一个可选的say命令可用。它相当于ruby的puts

use feature qw(say);
say "I get a newline automatically.";

请参阅perldoc feature

找到数组的长度

my $num = scalar @choices;   # or,
my $num = @choices;

数组的随机元素:

my $rand_elem = $choices[rand @choices];

答案 2 :(得分:0)

在Perl中,并非所有内容都自动成为对象,因此本身没有方法。函数称为子例程,或 sub 。您可以使用sub关键字创建一个。

sub foo {
  # ...
}

您可以使用标识符来调用它。在我们的例子中:

foo();

有关详细信息,请参阅 [代码维基] 1中链接的各种资源,或查看perlsub