Подсчет элементов массива в Perl

Как насчет упрощения вашего кода следующим образом (как упомянул @DublinDev):

return $(selector).filter((elem: ElementFinder) => {
    return elem.getText().then((text: string) => {
        return text === data;
    });
}).first().click();

Важна ли mouseMove в вашем случае?

Более того

.then(() => {
    Key.ENTER;
});
[116 ] в вашем примере на самом деле ничего не делает.

Пожалуйста, скажите мне, если это ускорило тест.

27
задан Peter Mortensen 15 August 2016 в 08:14
поделиться

4 ответа

Edit: Hash versus Array

As cincodenada correctly pointed out in the comment, ysth gave a better answer: I should have answered your question with another question: "Do you really want to use a Perl array? A hash may be more appropriate."

An array allocates memory for all possible indices up to the largest used so-far. In your example, you allocate 24 cells (but use only 3). By contrast, a hash only allocates space for those fields that are actually used.

Array solution: scalar grep

Here are two possible solutions (see below for explanation):

print scalar(grep {defined $_} @a), "\n";  # prints 3
print scalar(grep $_, @a), "\n";            # prints 3

Explanation: After adding $a[23], your array really contains 24 elements --- but most of them are undefined (which also evaluates as false). You can count the number of defined elements (as done in the first solution) or the number of true elements (second solution).

What is the difference? If you set $a[10]=0, then the first solution will count it, but the second solution won't (because 0 is false but defined). If you set $a[3]=undef, none of the solutions will count it.

Hash solution (by yst)

As suggested by another solution, you can work with a hash and avoid all the problems:

$a{0}  = 1;
$a{5}  = 2;
$a{23} = 3;
print scalar(keys %a), "\n";  # prints 3

This solution counts zeros and undef values.

39
ответ дан 28 November 2019 в 04:22
поделиться

распечатать скалярный grep {определенный $ _} @a;

8
ответ дан kcwu 28 November 2019 в 04:22
поделиться

Похоже, вам нужен разреженный массив . В нормальном массиве будет 24 элемента, а в разреженном массиве будет 3. В Perl мы имитируем разреженные массивы с помощью хешей:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

Функция keys в скалярном контексте вернет количество элементов в разреженный массив. Единственным недостатком использования хэша для имитации разреженного массива является то, что вы должны отсортировать ключи перед повторением по ним, если их порядок важен.

Вы также должны не забывать использовать функцию delete для удаления элементов из разреженного массива (просто установить для них значение undef недостаточно).

16
ответ дан 28 November 2019 в 04:22
поделиться

Может быть, вам нужен хеш вместо (или в дополнение). Массивы - это упорядоченный набор элементов; если вы создаете $ foo [23] , вы неявно создаете от $ foo [0] до $ foo [22] .

.
14
ответ дан 28 November 2019 в 04:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: