1

I am confused with the difference in the outputs of the following two snippets :

SNIPPET 1

use Data::Dumper; 
my $q = (   
          { q=>1,  w=>2 }, 
          { i=>8 }, 
); 
print "\nOUTPUT_1   $q=[".$q."] "; 

print "\nOUTPUT_2   ".Data::Dumper::Dumper ($q); 
$q[0]->{a} = "5"; 

print "\nOUTPUT_3   ".Data::Dumper::Dumper ($q);

OUTPUT

OUTPUT_1   HASH(0x872de10)=[HASH(0x872de10)]  
OUTPUT_2   $VAR1 = {
          'i' => 8
        };

OUTPUT_3   $VAR1 = {
          'i' => 8
        };

SNIPPET 2

use Data::Dumper; 
my $q = (
         { q=>1, w=>2 }, 
); 
print "\nOUTPUT_1   $q=[".$q."] "; 

print "\nOUTPUT_2   ".Data::Dumper::Dumper ($q); 
$q[0]->{a} = "5"; 

print "\nOUTPUT_3   ".Data::Dumper::Dumper ($q);

OUTPUT

OUTPUT_1   HASH(0x81861bc)=[HASH(0x81861bc)]  
OUTPUT_2   $VAR1 = {
          'w' => 2,
          'q' => 1
        };

OUTPUT_3   $VAR1 = {
          'w' => 2,
          'q' => 1
        };

I saw the second snippet being used in a production code. I tried to expand it in a way shown in Snippet 1 but failed.

MY UNDERSTANDING
When an array is assigned to a scalar, its count gets stored in that scalar. I believed that this holds good irrespective of the contents of the array.

I do not want a solution here but I want to correct my understanding.

mpapec
  • 50,217
  • 8
  • 67
  • 127
gsinha
  • 1,165
  • 2
  • 18
  • 43
  • 3
    What you have there isn't an array, it's a list. Furthermore look up what the comma operator does (it isn't only for array construction). – Patrick J. S. Feb 13 '15 at 09:51
  • 1
    I recommend that you read [`perldoc -q "difference between a list and an array"`](http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-between-a-list-and-an-array?) – Borodin Feb 13 '15 at 09:56
  • `use strict;` would tell you that `$q` in `$q[0]` is not same variable as `$q`, and you're dealing [with list, not an array](http://stackoverflow.com/questions/8232951/is-there-such-a-thing-as-a-list-in-scalar-context). – mpapec Feb 13 '15 at 10:52
  • PatrickJ.S., Borodin, Сухой27 Thanks for your replies. I am going though the links and trying out. Another good link which I found is [this](http://friedo.com/blog/2013/07/arrays-vs-lists-in-perl). – gsinha Feb 13 '15 at 12:28

1 Answers1

1

Have a look at List value constructors in perldata. You're not creating $q as an array ref, you're just assigning the last value in the list to $q. Hence any attempt to treat $q as an array ref won't work as you expect.

TobyLL
  • 2,098
  • 2
  • 17
  • 23