I liked the idea of using a hash - it should be more efficient than comparing every key to the entire list every time for large numbers of additions/substitutions.
use warnings;
use strict;
my @tied_array = ("a=1", "b=2", "c=3");
my %compare_hash;
#a little extra overhead in the beginning
#could be done more elegantly with map???
for( my $i=0; $i<@tied_array; $i++) {
my ($key, $val) = split /=/, $tied_array[$i];
#the index must be associated with the key
#so we know where it goes in the original array
$compare_hash{$key} = [$i, $val];
}
print join(",", @tied_array), "\n";
update("b", 22);#this replaces
print join(",", @tied_array), "\n";
update("d", 45);#this inserts
print join(",", @tied_array), "\n";
sub update {
my ($key, $val) = @_;
#checking for the existence of a key in a hash
#should be more efficient than grepping through
#what could be a very large array
if( defined $compare_hash{$key} ) {
unless( $compare_hash{$key}[1] eq $val ) {
$tied_array[$compare_hash{$key}[0]] = "$key=$val";
#overhead required to maintain the comparison hash
$compare_hash{$key}[1] = $val;
}
} else {
push @tied_array, "$key=$val";
#overhead required to maintain the comparison hash
$compare_hash{$key} = [$#tied_array, $val];
}
}
Update
Fixed use of square braces instead of curly ones when accessing hashes (PHP is rotting my brain!). |