On Tue, Oct 28, 2003 at 10:51:20PM +0100, B. Fongo wrote: > What may be wrong with my codes? Perl complains of use of uninitialized > value at addition and in range (or flop). > > #!/usr/bin/perl -w > use strict; > > my ($xi, $i, @numbers, @slice); > @numbers = (1..10); > $i = 0; > $xi = 0; > > open(RS, ">perd.dat") || die "Could not open file. $!\n"; > for (my $z = 0; $z <= $#numbers; $z++){ > foreach (@numbers){ > @slice = @numbers[$xi, $numbers[$i] .. $numbers[$i]+4]; > # Use of uninitialized value at here? > print RS "@slice\n"; > $i++; > } > $xi++; > }
You could write it more cleanly like this: my $path = 'perd.dat'; open my $rs, $path or die "open: $path: $!"; my @numbers = 1..10; for my $z (0..$#numbers) { for my $i (0..$#numbers) { print $rs @numbers[$z, $numbers[$i]..$numbers[$i]+4]; } } Which gets rid of some of the unused variables and uses the more perlish foreach() loop. The problem is that you're indexing off the end of @numbers -- I assumed that you meant to reset $i each time through the outer loop (?) which fixes part of the problem, but you still have the situation where $i > 4. Look at the result of this expression when $z = 0 and $i = 5. print $rs @numbers[$z, $numbers[$i] .. $numbers[$i] + 4]; --> print $rs @numbers[ 0, $numbers[5] .. $numbers[5] + 4]; --> print $rs @numbers[ 0, 6 .. 6 + 4]; --> print $rs @numbers[ 0, 6 .. 10 ]; --> print $rs @numbers[ 0, 6, 7, 8, 9, 10 ]; So the array slice yields: --> print $rs 1, 7, 8, 9, 10, undef; And this generates an "uninitialized value" warning. The next time through the inner loop, you end up with: print $rs @numbers[0, 7 .. 11] --> print $rs @numbers[0, 7, 8, 9, 10, 11] --> print $rs 1, 8, 9, 10, undef, undef; Which generates two warnings, and so forth. What are you really trying to do here? -- Steve -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]