Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Declaring and checking content of variables with consecutive names

by AnomalousMonk (Bishop)
on Sep 23, 2016 at 17:23 UTC ( #1172478=note: print w/replies, xml ) Need Help??


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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1172478]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2019-09-23 04:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The room is dark, and your next move is ...












    Results (276 votes). Check out past polls.

    Notices?