-1

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',
            };
simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 1
    It's not very clear what you're trying to do. What you call "Expected output" is not an expected output: it's a mix of (invalid) Perl code, (invalid) comments, and output... There are [some ways](https://stackoverflow.com/questions/418027/how-do-i-read-back-in-the-output-of-datadumper) to parse the output of Data::Dumper, but in general, it's better to use another format. Do you have control of the script generating the dumper? A bit more context could help. – Dada Apr 19 '22 at 10:30
  • Output from Data::Dumper->Dumper is Perl code, so it can be eval'd into Perl code. For example: `my @data = do './dumperoutput.txt';`. But be careful about what the file contains, since it is evaluated as code. – TLP Apr 19 '22 at 11:07

1 Answers1

1

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'
        };
simbabque
  • 53,749
  • 8
  • 73
  • 136