in reply to How could I simplify this redundant-column-removing code?

G'day rubystallion,

Welcome to the Monastery.

The approach I took was to read the spec, grab the DATA and write the code. I didn't spend a lot of time looking at your code initially; although, I have commented on it further down in my post. Here's what I came up with:

#!/usr/bin/env perl -l use strict; use warnings; no warnings 'uninitialized'; my @key_value_pairs; # Capture key-value pairs from original query strings while (<DATA>) { chomp; push @key_value_pairs, { map { (split /=/)[0,1] } split /&/ }; } # Remove common key-value pairs KEY: for my $key (keys %{$key_value_pairs[0]}) { for my $i (1 .. $#key_value_pairs) { next KEY unless $key_value_pairs[0]{$key} eq $key_value_pairs[ +$i]{$key}; } delete $key_value_pairs[$_]{$key} for 0 .. $#key_value_pairs; } # Recreate query strings without common key-value pairs for my $kvp (@key_value_pairs) { print join '&', map { join '=', $_, $kvp->{$_} } sort keys %$kvp; } __DATA__ a=1&b=1&c=1&d=2&e=&f=3 a=1&b=2&c=3&d=2&e=&f=4 a=1&b=2&c=5&d=1&e=&f=5

Output:

b=1&c=1&d=2&f=3 b=2&c=3&d=2&f=4 b=2&c=5&d=1&f=5

From the comments embedded in the code, you can see three distinct steps: capture all the initial data; remove the common data; recreate the query strings with what's left.

As you indicated (i.e. "in my head it's very simple") this was fairly straightforward:

  1. split on '&' and then on '='
  2. only delete if all equality tests are TRUE
  3. join with '=' and then with '&'
"Is there any way to make the code significantly simpler or make it easier for me to write something like this bug-free the first time?"

That's a little difficult to answer without knowing what you did on your first three attempts.

A couple of notes on command switches:

And, of course, if anything else in my code needs further explanation, just ask.

-- Ken

Replies are listed 'Best First'.
Re^2: How could I simplify this redundant-column-removing code?
by rubystallion (Novice) on Jun 18, 2015 at 03:54 UTC
    Hi Ken, Thanks for the suggestions. You're right, poorly named variables (or poor commenting) might have been the reason for one bug I had. Also good to know the advantages of the warnings pragma. I still needed a few minutes to get my head around your solution, but if I get more practise with nested commands and nested data structures this will hopefully become fairly straightforward for me, too.