Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

question about array usage 1

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
This is kinda a newbie one.

What's the difference between $array[0] and @array[0]?

I learnt that $array[0] is the first element in the array variable '@array' since day one. I have never seen any textbooks suggest using @array[0].

But in reality, I have seen both $array[0] and @array[0]. So, are they identical? If not, which one is better and why? A piece of sample codes to demo the difference is highly appreciated.
 
$array[index] references a scalar array element.

@array[range] references an array slice.

By using @array[0] you are referencing a single-element list containing the first element of the array. It works, but it's unnecessary, and with warnings enabled you get a message like the one highlighted in red below.

The example below also shows you how array slices are useful, for generating lists that are a subset of the original array. See the "Slices" section of perldoc perldata for a complete explanation and set of examples.

Code:
$ nl -ba whn2
     1  #!/usr/bin/perl -w
     2
     3  $|=1;
     4
     5  my @a;
     6
     7  $a[0]=1;
     8  $a[1]=2;
     9  $a[2]=4;
    10
    11  print "$a[0]\n";
    12  print "@a[0]\n";
    13  print "@a[0,2]\n";
    14  print "@a[1..2]\n";
$ ./whn2
[red]Scalar value @a[0] better written as $a[0] at ./whn2 line 12.[/red]
1
1
1 4
2 4
$

Annihilannic.
 
Thank you, Annihilannic!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top