views:

253

answers:

4

I am running perl, v5.6.1 built for sun4-solaris-64int

I am calling print on an array

print "@vals\n";

and the output looks like

HASH(0x229a4) uid cn attuid

or another example

@foo = {};
push(@foo, "c");

print "@foo I am done now\n";

with output of

HASH(0x2ece0) c I am done now

Where is HASH(0x2ece0) comming from?

Thanks Aaron

+12  A: 

Your braces in @foo = {} are creating it. The braces create an unnamed hash reference.

If you want to set @foo to an empty list, use @foo = ()

Zan Lynx
+4  A: 

You accidentally have a hash reference in @foo. When you print a reference out without dereferencing it (almost always by accident), you get a debugging string (the type of reference it is and a memory location).

I think you want my @foo = (); push @foo, "c"; rather than what you have now. On the other hand, you can also simply say my @foo; to create the array. You don't need to explicitly mark it as empty with ().

See perldoc perlreftut and perldoc perlref for more on references.

Telemachus
+3  A: 

Your code should be written like this:

use strict;
use warnings;

my @foo;
push @foo, "c";

print "@foo I am done now\n";

You don't need to initialize variables in Perl, if you want to have an empty variable. You should however use my to declare a local variable. And you don't need parentheses around built-in functions, that just adds clutter.

Peter Stuifzand
+4  A: 

The key to understanding this sort of problem is that you get an extra item in the output. It's not too important what that item is.

In general, the first thing you'd want to do when your container variable has more (or less) in it than you expect is to look at it's contents. The Data::Dumper module comes with Perl and can pretty print data structures for you:

use Data::Dumper;
print Dumper( \@foo );

Once you see what is in your container, you can start to work backward to find out how it got in there. You'd eventually end up noticing that right after you initialized @foo that it already had one element, which isn't what you wanted.

Another trick is to check the number of elements in the list:

print "There are " . @array . " elements in \@array\n";

If you get a number you don't expect, work backward to find out when the extra element showed up.

brian d foy