I'm learning Perl. I have been able to use grep
on an array and the syntax is very simple, like this example:
use strict; use warnings;
my @names = qw(Foo Bar Baz);
my $visitor = <STDIN>;
chomp $visitor;
if (grep { $visitor eq $_ } @names) {
print "Visitor $visitor is in the guest list\n";
} else {
print "Visitor $visitor is NOT in the guest list\n";
}
However, I would like to know if there is an equally simple way to use grep
on a hash without coding a loop to iterate through each item in the hash.
Here is some example data with the structure I'm working with. Before assigning a URI, I want to check if any item has that uri value already. For example, I want to assign ww1.example.com
to item v2rbz1568
, but only if no other item has a uri value of ww1.example.com
. How can I efficiently accomplish that in Perl?
{
"0y7vfr1234": {
"username": "[email protected]",
"password": "some-random-password123",
"uri": "ww1.example.com",
"index": 14
},
"v2rbz1568": {
"username": "[email protected]",
"password": "some-random-password125",
"uri": "ww3.example.com",
"index": 29
},
"0zjk1156": {
"username": "[email protected]",
"password": "some-random-password124",
"uri": "ww2.example.com",
"index": 38
}
}
I'm using perl 5, version 30 on Linux.
grep { ... } values %$hash_ref
. Your question has nothing to do with Unix and is too basic to be useful (you could've gathered that and more with a simple search).