简体   繁体   中英

Some errors in Perl for reasons that I don't know

I am just making a program (as I'm bored) that converts English sentence to Pig Latin. The code looks extremely fine to me however it throws errors when I input a sentence. I don't know why is it giving the errors.

The Code:

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";

The errors:

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 

The documentation says:

substr EXPR,OFFSET,LENGTH

You have your arguments reversed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM