Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Consise way to filter out keys with undef values from a hash slice?

by LanX (Saint)
on Jun 01, 2020 at 21:16 UTC ( [id://11117572]=note: print w/replies, xml ) Need Help??


in reply to Consise way to filter out keys with undef values from a hash slice?

This

>  grep { $args{$_ } } keys %ta;

Will also delete all false values like 0 or "" . You rather want to test on definedness and not truth

This keys on a slice

>   keys %args{'profile', 'user', 'password'};

Is over complicated and doesn't make sense.

You obviously just want the list of keys directly

'profile', 'user', 'password'

But I concur with choroba that using exists right from the beginning is the cleanest way, since undef could be a legal value.

edit

There is - unfortunately - no "slice when exists" operator in Perl.

Otherwise (ab)using hashes for set operations like intersections would be trivial.

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Consise way to filter out keys with undef values from a hash slice?
by LanX (Saint) on Jun 01, 2020 at 22:00 UTC
    On a side note,

    I was surprised that the following is even legal syntax. I only knew slicing lists with @

    >  %args{'profile', 'user', 'password'};

    Turns out it was introduced with 5.20 and returns a list of key/value pairs.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Re^2: Consise way to filter out keys with undef values from a hash slice?
by jo37 (Deacon) on Jun 02, 2020 at 19:05 UTC
    Otherwise (ab)using hashes for set operations like intersections would be trivial.

    Though off-topic here: Is there a common idiom for an intersection of two hash-sets? The first thing that comes to my mind is something like:

    %a_b = map {exists $b{$_} ? ($_ => $b{$_}) : ()} keys %a;

    Greetings,
    -jo

    $gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-24 04:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found