Lexical arrays and hashes are created empty. You can create a new lexical array or hash with my
:
my @array;
my %hash;
For the most part, you should only be using lexical arrays and hashes, but you can create package arrays and hashes with our
:
our @array;
our %hash;
@array
and %hash
may or may not have data in them in this case (if they were previously created, this will not clear their contents). The names of these variables are lexically scoped, but the data is package scoped, so if you say:
{
our @a = (1 .. 5);
}
{
our @a;
print "@a\n";
}
It will still print "1 2 3 4 5\n"
.
There are many ways to clear a hash or array. The most common is to assign an empty list to it:
@array = ();
%hash = ();
You can also use undef
to clear a hash or array:
undef @array;
undef %hash;
You could also pop
, shift
, or splice
items off of an array:
pop @array while @array;
shift @array while @array;
splice @array, 0, scalar @array;
You can also modify the number of elements in and an array by assigning a number to the $#array
form of its name. If you assign a negative value, the array is emptied:
$#array = -1;