What does it mean when you try to print an array or hash using Perl and you get, Array(0xd3888)?

前端 未结 3 1445
余生分开走
余生分开走 2020-12-06 17:08

What does it mean when you try to print an array or hash and you see the following; Array(0xd3888) or HASH(0xd3978)?

EXAMPLE

CODE

my @data =          


        
3条回答
  •  醉话见心
    2020-12-06 17:27

    You're printing a reference to the hash or array, rather than the contents OF that.

    In the particular code you're describing I seem to recall that Perl automagically makes the foreach looping index variable (my $line in your code) into an "alias" (a sort of reference I guess) of the value at each stage through the loop.

    So $line is a reference to @data[x] ... which is, at each iteration, some array. To get at one of the element of @data[0] you'd need the $ sigil (because the elements of the array at @data[0] are scalars). However $line[0] is a reference to some package/global variable that doesn't exist (use warnings; use strict; will tell you that, BTW).

    [Edited after Ether pointed out my ignorance] @data is a list of anonymous array references; each of which contains a list of scalars. Thus you have to use the sort of explicit de-referencing I describe below:

    What you need is something more like:

    print ${$line}[0], ${$line}[1], ${$line}[2], "\n";
    

    ... notice that the ${xxx}[0] is ensuring that the xxx is derefenced, then indexing is performed on the result of the dereference, which is then extracted as a scalar.

    I testing this as well:

    print $$line[0], $$line[1], $$line[2], "\n";
    

    ... and it seems to work. (However, I think that the first form is more clear, even if it's more verbose).

    Personally I chalk this up to yet another gotchya in Perl.

    [Further editorializing] I still count this as a "gotchya." Stuff like this, and the fact that most of the responses to this question have been technically correct while utterly failing to show any effort to actually help the original poster, has once again reminded me why I shifted to Python so many years ago. The code I posted works, of course, and probably accomplishes what the OP was attempting. My explanation was wholly wrong. I saw the word "alias" in the `perlsyn` man page and remembered that there were some funky semantics somewhere there; so I totally missed the part that [...] is creating an anonymous reference. Unless you drink from the Perl Kool-Aid in deep drafts then even the simplest code cannot be explained.

提交回复
热议问题