in reply to Re: Re: Inserting lines in a file with Tie::File if lines don't exist
in thread Inserting lines in a file with Tie::File if lines don't exist

It is fine to stay with array. Hope the following code helps:

Made a general purpose function to handle both replace and insert, and determines whether to insert or replace on its own:

use warnings; use strict; my @a = ("a=1", "b=2", "c=3"); print join(",", @a), "\n"; add("b", 22);#this replaces print join(",", @a), "\n"; add("d", 45);#this inserts print join(",", @a), "\n"; sub add { my ($key, $val) = @_; my $exists = 0; for (grep /^$key=/, @a) { $_ = "$key=$val"; $exists = 1; } if (!$exists) { push @a, "$key=$val" } }
  • Comment on Re: Re: Re: Inserting lines in a file with Tie::File if lines don't exist
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: Re: Inserting lines in a file with Tie::File if lines don't exist
by devgoddess (Acolyte) on Dec 31, 2003 at 01:54 UTC
    Oh, COOL... That's great! I think I can make it work. But tomorrow. Not tonight. I have a headache, and it's screaming for Excedrin. ;) I'll let you know how it works out. THANK YOU!
    Dev Goddess
    Developer / Analyst / Criminal Mastermind

    "Size doesn't matter. It's all about speed and performance."

Re: Re: Re: Re: Inserting lines in a file with Tie::File if lines don't exist
by bean (Monk) on Dec 31, 2003 at 20:34 UTC
    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!).