Say I define an array as:
my @my_array = ["hello", "world"]
Is there any difference between using $my_array vs \@my_array later in my code?
I presume that they are both are scalar references to @array, but I think I have seen one of my programs behaving differently depending on which one I use.
Is there any difference at all between them?
@array is array$var is scalar\@array is scalar - reference to array @array("hello", "world") is list (compatible with @array)["hello", "world"] scalar, reference to array. It is the same as storing array ("hello", "world") in variable @array and then taking reference \@array from it.When you use:
my $my_array = ["hello", "world"]
you create variable $my_array which is reference to array ("hello", "world").
When you use:
my @my_array = ["hello", "world"]
you create an array which contains single element: reference to array ("hello", "world").
Is there a difference between \@my_array and $my_array? It depends:
my @my_array = qw(hello world); #Note the use of parentheses
my $my_array = "Hello, I am just some random string!";
In the above case, there is a difference between \@my_array and $my_array. Likeness in variable names don't necessarily imply a relationship.
However:
my @my_array qw(hello world);
my $my_array = \@my_array;
\@my_array and $my_array would be identical. A change in @my_array would be reflected in the reference $my_array.
In your code you have:
my @my_array = ["hello", "world"];
Which is really a strange syntax...
[...] syntax is defining a reference to an array. Most of the time, you'd see something like this:
my $array_ref = ["hello", "world"]; #Note the assignment to a scalar and not an array
or this:
my @my_array = ("hello", "world"); #Note the parentheses and not straight brackets
Look at this program using Data::Dumper:
use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
my @my_array = ["hello", "world"];
say Dumper \@my_array;
The output is:
$VAR1 = [
[
'hello',
'world'
]
];
What this is saying is that there's an array of a single element (that is, your @my_array only contains $my_array[0]), and that element in that array is a reference to another array that contains two elements 'hello', and 'world'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With