1

我只是在制作一个将英语句子转换为 Pig Latin 的程序(因为我很无聊)。该代码对我来说看起来非常好,但是当我输入句子时它会引发错误。我不知道为什么它会给出错误。

编码:

use strict;
use warnings;

sub to_pig_latin
{
    my $sentence = shift;
    my @words = split(" ", $sentence);
    my $translated = " ";
    my $cw;
    for(my $i = 0; $i < scalar(@words); $i++)
    {
        my $word = $words[$i];
        if($word eq "." or $word eq "!" or $word eq "?")
        {
        }
        else
        {
            $cw = substr(1, length($word)-1, $word);
            $translated = $translated.$cw.substr(0,1,$word)."ay"." ";
        }
    }
    return $translated;
}
print "Welcome to English -> Pig Latin Converter.\n";
print "Enter an English sentence to translate:\n";
my $to_translate = <STDIN>;
chomp($to_translate);
print " ";
my $translated = to_pig_latin($to_translate);
print "Translated sentence:$translated\n";

错误:

Welcome to English -> Pig Latin Converter.
Enter an English sentence to translate:
Hello World!
Argument "Hello" isn't numeric in substr at pig_latin.pl line 18, <STDIN> line 1.
substr outside of string at pig_latin.pl line 18, <STDIN> line 1.
Use of uninitialized value $cw in concatenation (.) or string at pig_latin.pl line 19, <STDIN> line 1.
Argument "World!" isn't numeric in substr at pig_latin.pl line 18, <STDIN> line 1.
substr outside of string at pig_latin.pl line 18, <STDIN> line 1.
Use of uninitialized value $cw in concatenation (.) or string at pig_latin.pl line 19, <STDIN> line 1.
 Translated sentence: ay ay 
4

1 回答 1

7

文档说:

substr 表达式,偏移量,长度

你的论点颠倒了。

于 2013-08-12T16:37:29.547 回答