chris chris - 2 years ago 119
Perl Question

perl: printing object properties

I'm playing a bit with the Net::Amazon::EC2 libraries, and can't find out a simple way to print object properties:

This works:

my $snaps = $ec2->describe_snapshots();
foreach my $snap ( @$snaps ) {
print $snap->snapshot_id . " " . $snap->volume_id . "\n";

But if I try:

print "$snap->snapshot_id $snap->volume_id \n";

I get


Is there a simple way to print the value of the property inside a print?

Answer Source

Not in the way you want to do it. In fact, what you're doing with $snap->snapshot_id is calling a method (as in sub). Perl cannot do that inside a double-quoted string. It will interpolate your variable $snap. That becomes something like HASH(0x1234567) because that is what it is: a blessed reference of a hash.

The interpolation only works with scalars (and arrays, but I'll omit that). You can go:

print "$foo $bar"; # scalar
print "$hash->{key}"; # scalar inside a hashref
print "$hash->{key}->{moreKeys}->[0]"; # scalar in an array ref in a hashref...

There is one way to do it, though: You can reference and dereference it inside the quoted string, like I do here:

use DateTime;
my $dt = DateTime->now();
print "${\$dt->epoch }"; # both these
print "@{[$dt->epoch]}"; # examples work

But that looks rather ugly, so I would not recommend it. Use your first approach instead!

If you're still interested in how it works, you might also want to look at these Perl FAQs:

From perlref:

Here's a trick for interpolating a subroutine call into a string:

print "My sub returned @{[mysub(1,2,3)]} that time.\n";

The way it works is that when the @{...} is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to mysub(1,2,3) . So the whole block returns a reference to an array, which is then dereferenced by @{...} and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions:

print "That yields @{[$n + 5]} widgets\n";

Similarly, an expression that returns a reference to a scalar can be dereferenced via ${...} . Thus, the above expression may be written as:

print "That yields ${\($n + 5)} widgets\n";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download