Extract information from Dumper

107 views Asked by At

How to extract partial information from Dumper data with a key?

$VAR1 = {
          'fruit' => 'apple',
          'uniqueID' => 'red'
        };
$VAR2 = {
          'fruit' => 'apple',
          'uniqueID' => 'green',
        };

Expected output

key = green
my @found;

If key is in data (search for uniqueID),
found =     $VAR2 = {
              'fruit' => 'apple',
              'uniqueID' => 'green',
            };
1

There are 1 answers

0
simbabque On

It looks like you have a list of data structures, that you are passing to Data::Dumper.

my @all_results = (
    {
        'fruit'    => 'apple',
        'uniqueID' => 'red'
    },
    {
        'fruit'    => 'apple',
        'uniqueID' => 'green',
    },
);

print Dumper @all_results;

That would produce the output with $VAR1 and $VAR2 you've shows in the question.

Now if you want to search for the data structure inside @all_results where the key uniqueID is "green", you can use grep to look into every data structure, and filter out only the one you want.

( my $filtered ) = grep { $_->{'uniqueID'} eq 'green' } @all_results;
print Dumper $filtered;

Note that you need the parentheses () around the new variable, as grep returns a list. You need to assign in list context, otherwise you'll get the number of elements of the result back. (That's 1 in this case).

The output of above code is

$VAR1 = {
          'uniqueID' => 'green',
          'fruit' => 'apple'
        };