迭代perl对象数组

时间:2013-09-06 09:13:21

标签: perl selenium moose

我在perl中有这个对象

$ elem = $ driver-> get_elements(“//选择[\ @ name [\”cars \“] //选项”);

<code><pre>
    1  Selenium::Remote::WebElement=HASH(0x600f700)
      'driver' => Selenium::Remote::Driver=HASH(0x5bb9618)
         -> REUSED_ADDRESS
      'id' => 95
    2  Selenium::Remote::WebElement=HASH(0x6012d18)
      'driver' => Selenium::Remote::Driver=HASH(0x5bb9618)
         -> REUSED_ADDRESS
      'id' => 96
    3  Selenium::Remote::WebElement=HASH(0x5ff29f8)
      'driver' => Selenium::Remote::Driver=HASH(0x5bb9618)
         -> REUSED_ADDRESS
      'id' => 97
    4  Selenium::Remote::WebElement=HASH(0x5ca26b8)
      'driver' => Selenium::Remote::Driver=HASH(0x5bb9618)
         -> REUSED_ADDRESS
      'id' => 98
    5  Selenium::Remote::WebElement=HASH(0x600b330)
      'driver' => Selenium::Remote::Driver=HASH(0x5bb9618)
         -> REUSED_ADDRESS
      'id' => 99

现在我想迭代$ elem中的每个数组元素。 怎么会这样呢?

2 个答案:

答案 0 :(得分:1)

您需要取消引用$elem,然后循环:

for my $element (@{ $elem }) {
    # do stuff
}

答案 1 :(得分:1)

Selenium::Remote::Driver没有get_elements功能,据我在文档中看到。相反,存在find_elements。它将在列表上下文中返回一个平面数组,或在标量上下文中返回一个数组引用。也就是说,你可以做到

my @elems = $driver->find_elements(...);
for my $elem (@elems) {
  ...
}

my $elems = $driver->find_elements(...)
for my $elem (@$elems) {
  ...
}

有关如何使用参考的更多信息,请阅读perlreftut