perl:打印对象属性 [英] perl: printing object properties

查看:86
本文介绍了perl:打印对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Net::Amazon::EC2 库,但找不到打印对象属性的简单方法:

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

这有效:

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

但如果我尝试:

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

我明白了

Net::Amazon::EC2::Snapshot=HASH(0x4c1be90)->snapshot_id

是否有一种简单的方法可以在打印件中打印属性的值?

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

推荐答案

不是你想要的方式.事实上,您对 $snap->snapshot_id 所做的就是调用一个方法(如在 sub 中那样).Perl 不能在双引号字符串中做到这一点.它将插入您的变量 $snap.这变成了类似于 HASH(0x1234567) 的东西,因为它是这样的:散列的 bless 引用.

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!

如果您仍然对其工作原理感兴趣,您可能还想查看这些 Perl 常见问题解答:

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

来自 perlref:

这里有一个将子程序调用插入到字符串中的技巧:

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

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

它的工作方式是当@{...} 出现在双引号中时字符串,它被评估为一个块.该块创建对一个的引用包含调用 mysub(1,2,3) 的结果的匿名数组.所以整个块返回一个对数组的引用,然后被@{...} 取消引用并卡在双引号字符串中.这Chicanery 对任意表达式也很有用:

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";

这篇关于perl:打印对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆