Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is $my_array different from \@my_array?

Tags:

perl

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?

like image 225
Amelio Vazquez-Reina Avatar asked Apr 12 '26 05:04

Amelio Vazquez-Reina


2 Answers

  • @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").

like image 73
mvp Avatar answered Apr 14 '26 22:04

mvp


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'.

like image 31
David W. Avatar answered Apr 14 '26 22:04

David W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!