Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

raku

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.

like image 630
pcarrier Avatar asked May 28 '18 17:05

pcarrier


3 Answers

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)
like image 175
Christoph Avatar answered Nov 17 '22 02:11

Christoph


This will do:

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

Alternatively, you can look at splice.

like image 32
nxadm Avatar answered Nov 17 '22 02:11

nxadm


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
like image 22
Joshua Avatar answered Nov 17 '22 01:11

Joshua