The problem is that you are using global variables throughout, so they are keeping their values across iterations of the loop. You have reset @words
to an empty list even though you didn't need to - it is overwritten when you assign the result of split
to it - but $k
is increasing endlessly.
$k
is initially set to undef
which evaluates as zero, so for the first sentence everything is fine. But you leave $k
set to the number of elements in @words
so it starts from there instead of from zero for the next sentence. Your loop over @words
becomes endless because you are assigning to (and so creating) $words[$k]
so the array is getting longer as fast as you are looping through it.
The same problem applies to $i
and $j
, but execution never gets as far as reusing those.
Alshtough this was the only way of working in Perl 4, over twenty years ago, Perl 5 has made programming very much nicer to write and debug. You can now declare variables with my
, and you can use strict
which (among other things) insists that every variable you use must be declared, otherwise your program won't compile. There is also use warnings
which is just as invaluable. In this case it would have warned you that you were using an undefined variable $k
etc. to index the arrays.
If I apply use strict
and use warnings
, declare all of your variables and initialise the counters to zero then I get a working program. It's still not very elegant, and there are much better ways of doing it, but the error has gone away.
use strict;
use warnings;
my @input = <STDIN>;
my @output;
my $i = 0;
foreach (@input) {
# readability
my $lines = $_;
# split sentence
my @words = split ' ', $lines;
# capitalize each word
my $k = 0;
foreach (@words) {
$words[$k] = ucfirst;
$k++;
}
# join sentences again
$lines = join ' ', @words;
#create output line
$output[$i] = $lines;
$i++;
}
print "\nResult:\n";
my $j = 0;
foreach (@output) {
print $output[$j], "\n";
$j++;
}