I am using the the below Array of Hashes and would like to only display the most recent hash based off the ‘Datetime’, if four certain parameters are the same. Let me provide an example using the code below…
If ‘toy, kind, Stage, Step’ are the same, then I would only like to store only that hash into a new array of hashes.
Original Array of Hashes
$VAR1 = [
{
'Color' => 'green',
'2nd Color' => 'blue',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'ford',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:49:19'
},
{
'Color' => 'red',
'2nd Color' => 'green',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'ford',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:46:17'
},
{
'Color' => 'red',
'2nd Color' => 'blue',
'3rd Color' => 'green',
'toy' => 'truck',
'toy_type' => 'chevy',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:52:14'
},
{
'Color' => 'red',
'2nd Color' => 'blue',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'chevy',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:24:14'
},
{
'Color' => 'white',
'2nd Color' => 'blue',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'gmc',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 06:24:14'
},
New Array of Hashes I want saved to a variable:
$VAR2 = [
{
'Color' => 'green',
'2nd Color' => 'blue',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'ford',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:49:19'
},
{
'Color' => 'red',
'2nd Color' => 'blue',
'3rd Color' => 'green',
'toy' => 'truck',
'toy_type' => 'chevy',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 01:52:14'
},
{
'Color' => 'white',
'2nd Color' => 'blue',
'3rd Color' => 'yellow',
'toy' => 'truck',
'toy_type' => 'gmc',
'kind' => '4door',
'Stage' => 'Production',
'Step' => 'Platform',
'Datetime' => '2012/06/08 06:24:14'
},
Notice how I only wanted the most recent ford and recent chevy to be stored, but because there was only one gmc, I also wanted that stored.
I was referring to the perldsc (http://perldoc.perl.org/perldsc.html) documentation, but it did not go into this great of detail. Is this even possible?
The above method preserves the original order. It also handles ties elegantly (keeps both).
If you don’t need to preserve the original order, you can use something simpler. Unfortunately, it only keeps one record in the event of a tie, and its performance doesn’t scale as well [O(N log N) instead of O(N)].
(Add a
reversein front ofgrepif you want the final result sorted by ascendingDatetime.)