http://www.perlmonks.org?node_id=1172478


in reply to Declaring and checking content of variables with consecutive names

... find out (in a loop) which of those are empty?

One way for an array:

c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; use constant INITIALIZER => ''; ;; my @strings = (INITIALIZER) x 6; dd \@strings; ;; @strings[1, 4] = qw(foo bar); dd \@strings; ;; my @empties = grep { $strings[$_] eq INITIALIZER } 0 .. $#strings; print qq{indices of empty elements: @empties}; " ["", "", "", "", "", ""] ["", "foo", "", "", "bar", ""] indices of empty elements: 0 2 3 5
And a way for hashes:
c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; use constant INITIALIZER => ''; ;; my %strings = map { $_ => INITIALIZER } 0 .. 5; dd \%strings; ;; @strings{1, 4} = qw(foo bar); dd \%strings; ;; my @empties = grep { $strings{$_} eq INITIALIZER } keys %strings; print qq{keys of empty values: @empties}; " { "0" => "", "1" => "", "2" => "", "3" => "", "4" => "", "5" => "" } { "0" => "", "1" => "foo", "2" => "", "3" => "", "4" => "bar", "5" => +"" } keys of empty values: 3 0 2 5
(Keys of empty values are returned in random-ish order because hashes have no inherent ordering other than the key-value pairing of each hash element.)

Update: From Perl version 5.12 onward, keys called in list context also acts with arrays to return a list of all the indices (the "keys", get it?) of the array, so in the array example, the statement
    my @empties = grep { $strings[$_] eq INITIALIZER } keys @strings;
would have worked as well.


Give a man a fish:  <%-{-{-{-<