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]; } }
In reply to Re: Re: Re: Re: Inserting lines in a file with Tie::File if lines don't exist
by bean
in thread Inserting lines in a file with Tie::File if lines don't exist
by devgoddess
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |