Perl syntax that I don't understand.

I'm just trying to confirm that I understand someone's code correctly.

If someone has code that says:

$foo ||= mysub();

I'm assuming that it means if $foo is nothing or undef, then assign it some value via mysub(). If I'm wrong on this, please let me know.

Also, what's the difference between this:

$somescalar = [['one','two'],['three','four']];

and this:

@myarray = (['one','two'],['three','four']);

I'm assuming they both do the same thing and create a new list of lists in memory. The first one is a reference to the list of lists while the other is the actual list(array) of lists itself. If I'm wrong here, please let me know. I'm probably only 40-70 hours into perl. I've coded in other languages before, but syntax is usually the big hurdle for me.

For the first part you are right. For the second not really... To understand those two lines of code easier, run this script:

#!/usr/bin/perl
use Data::Dumper;
@myarray = [['one','two'],['three','four']];
print &Dumper(\@myarray);
@myarray = (['one','two'],['three','four']);
print &Dumper(\@myarray);

It will result in this:

solaris% ./b.pl 
$VAR1 = [
          [
            [
              'one',
              'two'
            ],
            [
              'three',
              'four'
            ]
          ]
        ];
$VAR1 = [
          [
            'one',
            'two'
          ],
          [
            'three',
            'four'
          ]
        ];

As you can see first line of code resulted in one more "level" of reference. This is because it created single element array that it's only element is reference to array containing references to lower level arrays. In simple words, first code is not what you would usually want to use :wink:

@bartus: but he's assigning it into a scalar:

$somescalar = [['one','two'],['three','four']];

So he'll end up with $somescalar being a reference to an anonymous array.

@mrwatkin:
You are right. The first construct will create a reference to an array. You can access the array elements through -> operator, like

$el11 = $somescalar->[1][1];   #el11 == "four"
$el11 = $myarray[1][1];  #el11 == "four"

Except the array is initialized straight there, instead of doing:

@myarray = (['one','two'],['three','four']);
$somescalar = \@myarray;

The advantage of working with references is that when you are passing them through a function, you are just passing an address to memory, instead of copying the whole thing over (passing by value).

BTW, in defining the @myarray you are using the anonymous array construct also: ['one','two'] will yield a reference to an array containing 'one' and 'two'.

He wasn't assigning into scalar before he edited the post :wink: And I was too lazy to change my post after he edited his.

ahhh.... It looked suspicious to me, I have to admit. :slight_smile:

@mrwatkin: Not a good idea to change your original post -- people who come across this thread later will be confused.