in reply to Initialization of arrays

@x[1..3] = 1;

The left is an array slice; it's expecting a list on the right. The "list" you gave it is essentially like (1, undef, undef). So only $x[1] is getting a value here. You could write it like:

@x[1..3] = (1,1,1)

For this:

for($y=0; $y!=@x; $y++)

You should generally avoid the C-style for. You can rewrite it like this:

for my $y (0..$#x)

Also to easily view the contents of your array without having to loop, you may look into Data::Dumper.

edit: Fixed as per [id://ikegami]'s reply

Replies are listed 'Best First'.
Re^2: Initialization of arrays
by ikegami (Patriarch) on Sep 22, 2005 at 14:02 UTC

    You can rewrite it like this:
    for my $y (0..@x)

    You mean:
    for my $y (0..$#x)

      For times when I access the last element of an array, I use @array[-1]; however, when I need to know the value of the last index, such as in a loop above, I have seen people recommend two approaches. Let's use the for snippet from the above -- it could be written in either of:

      for my $y (0..@x-1) { } # or # for my $y (0..$#x) { }

      Is there a practical difference?

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law

        There might be an extra op in the @x-1 version, but using the latter because of this would be "premature optimization". Pick whichever one you prefer. Personally, I prefer beating around the bush and use last ($#x) if I mean last, and count (@x) if I mean count. The down side is that the reader must be familiar with both ops.

        But that's assuming (deprecated) $[ is left untouched.. If $[ is 1, they're both wrong. The solution for $[ = 1 is
        for my $y (1..$#x) { }
        or
        for my $y (1..@x) { }
        and the general solution is
        for my $y ($[..$#x) { }
        or
        for my $y ($[..$[+@x-1) { }

Re^2: Initialization of arrays
by Tanktalus (Canon) on Sep 22, 2005 at 14:53 UTC