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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

square brackets? 1

Status
Not open for further replies.

rotis23

Programmer
Aug 29, 2002
121
GB
Hi All,

What's the difference between declaring an array using square or normal brackets?

Does it create a reference if they're square?

Thanks, rotis23
 
rotis23,

I think you've got it right.

my @array = [] is an annoymous array and my @array = () is an empty list.

Code:
my @array = [];
print "With []: \|@array\|\n";

my @array1 = ();
print "With (): \|@array1\|\n";
produces output similar to:
Code:
With []: |ARRAY(0x1abf0b4)|
With (): ||
 
my @array = [] is an annoymous array
To quibble, that's not quite true. @array is an array (not anonymous, it has a name) whose 1 element is a reference to an anonymous array. E.g.
Code:
#!perl
use strict;
use warnings;

my @array = [];
print "With []: \|@array\|\n";
[b]print scalar(@array), "\n";[/b]
print "\n";
my @array1 = ();
print "With (): \|@array1\|\n";
[b]print scalar(@array1), "\n";[/b]
print "\n";
[b]my $aref = [];
print "With (): \|$aref\|\n";
print scalar(@$aref), "\n";[/b]
Output:
Code:
With []: |ARRAY(0x225084)|
1

With (): ||
0

With (): |ARRAY(0x225138)|
0
Note the difference between @array and $aref.
@array is an array whose one element is a reference to an anonymous array. $aref is a reference to an empty anonymous array.

 
my @array = []; is the equivalent of
my @array = ( [ ] );
Because you're assigning to an array, the parens are implied.

In my $aref = [];, assignment to a scalar, no parens implied.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top