pcarrier
pcarrier

Reputation: 151

perl6: Array; get rid of empty slot (Any)

For an Array containing only Str elements, I can use grep(Str) in order to eliminate empty slot following a :delete;

For example:

my @prov_cd = <AB BC MB NB NL NS ON PE QC SK>;

@prov_cd[2]:delete;                              # Manitoba deleted

@prov_cd;                                        # [AB BC (Any) NB NL NS ON PE QC SK]

my @prov_cd_cleanup = @prov_cd.grep(Str);        # get rid of (Any) empty slot: [AB BC NB NL NS ON PE QC SK]

@prov_cd = @prov_cd_cleanup;                     # [AB BC NB NL NS ON PE QC SK]

An Array can contain a variety of object types; I would prefer to "grep" everything that is not (Any).

How can I do this ?

Thank you.

Upvotes: 7

Views: 156

Answers (3)

elcaro
elcaro

Reputation: 2307

To echo the above sentiments and provide an example, you can instead use splice, which also returns the value "spliced" if needed.

my @prov_cd = <AB BC MB NB NL NS ON PE QC SK>;

# Starting from index 2, remove the next 1 items
my $removed = @prov_cd.splice(2, 1);

say @prov_cd;  # OUTPUT: [AB BC NB NL NS ON PE QC SK]
say $removed;  # OUTPUT: [MB]

Note that splice always returns an Array, even if you only removed 1 item.

say $removed.^name;  # OUTPUT: Array

Upvotes: 2

nxadm
nxadm

Reputation: 2079

This will do:

@prov_cd.grep(*.defined) (AB BC NB NL NS ON PE QC SK)

Alternatively, you can look at splice.

Upvotes: 5

Christoph
Christoph

Reputation: 169613

First, note that if you remove entries via splice instead of :delete, the items will be shifted and no 'holes' will be generate.

Now, if you truly want to filter out just Any, you may do so via

@prov_cd.grep(* !=== Any)

However, I suspect you're looking for

@prov_cd.grep(*.defined)

Upvotes: 6

Related Questions