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!).

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.