Duong Nguyen wrote:
>
> Hello everyone,
Hello,
> Sorry for the spam,
Why do you think that this is spam?
> I am new to Perl and am having a hard time manipulating
> arrays. Below is the sample code that I am working on:
You should have warnings and strictures enabled while you are developing
your program.
use warnings;
use strict;
> @array1[0..5] = 1;
You are assigning a single value to an array slice. This means that
$array[0] gets the value 1 and $array[1] through $array[5] get the value
undef. It also means that the values in $array[6] through
$array[$#array] are not affected by the assignment. If this is the
first time that you are using @array then you need to assign a list of
six ones to the varaible @array.
my @array = ( 1, 1, 1, 1, 1, 1 );
Or, less error prone:
my @array = ( 1 ) x 6;
Or even (ick):
my @array = map 1, 0 .. 5;
> @total[0] = 0;
An array slice again! Perhaps you meant:
my $total = 0;
> for($i=0; $i<4; $i++)
In perl, that is usually written as:
for my $i ( 0 .. 3 )
But you are only totaling the first four elements of @array and the
array has at least six elements.
> {
> if($i == 0)
You don't need a special case for the zero element as perl uses
autovivification.
> {
> @total[$i] = @array1[$i];
> print @total[$i];
You are using array slices where you should be using scalars.
$total[$i] = $array1[$i];
print $total[$i];
> }
> else
> {
> $j = $i - 1;
> @total[$i] = @total[$j] + @array1[$i];
> print @total[$i];
Again, you are using array slices where you should be using scalars.
$total[$i] = $total[$j] + $array1[$i];
print $total[$i];
> }
> }
>
> This code would work in C/C++,
No, the algorithm is wrong.
> but with Perl, instead of adding up the
> previous values, the array "Total" seems to treat the integer value as
> a string and join them together.
No, it is just printing '1' each time through the loop.
> So instead of ending up with 4 as my
> resulting total, I instead get 1111.
That is because you are printing '1' four times.
> I know this is a rather dumb
> question, but any help would be GREATLY appreciated. Thanks in advance.
my @array = ( 1 ) x 6;
my $total = 0;
$total += $_ for @array[ 0 .. 3 ]; # now is a GOOD time for an array
slice
print "$total\n";
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>