On May 9, 1:29 pm, demianricca...@gmail.com (D) wrote:
> Hello everyone,
>
> I would like to learn an efficient way to change a single column in a
> file that is accessed by an external program after the column is
> changed each time.  open write close is what I have been using.  I
> thought that tieing could help speed it up.  While I didn't dig in too
> deeply, my split entry, change value and rejoin didn't seem to gain me
> much speed.  The test file and script are pasted below.  In practice
> the file will be about 100 lines long and the 3rd column will be
> rewritten thousands of times.  Is there a more efficient approach?
>
> example file:
>
> 'test'
> -------------
>   foo   ab     0
>  fooa    b     0
>  foob   cd     0
>   foo    e     0
>  fooc    f     0
>   foo   ab     0
>  fooa    b     0
>  foob   cd     0
>   foo    e     0
>  fooc    f     0
> -------------------------
>
> script:
> -------------------------------
> use IO::All;
> use warnings;
> use strict;
>
> my $lines = io('test')->new;
>
> print "$_ \n" foreach @$lines;
> print "\n\n\n\n\n";
>
> my @tmp;
> foreach (0 .. $#{$lines}){
>  $tmp[$_] = $_;
>
> }
>
> @$lines = map {
>                 my @sh = split /\s+/, $lines->[$_];
>                 join("   ",$sh[0],$sh[1],$tmp[$_]);
>               } 0 .. $#{$lines};
>
> --------------------------
>
> cat test:
>
> foo   ab   0
> fooa   b   1
> foob   cd   2
> foo   e   3
> fooc   f   4
> foo   ab   5
> fooa   b   6
> foob   cd   7
> foo   e   8
> fooc   f   9
> foo   ab   10

the tie that you mentioned is actually a decent
alternative if  speed's  not an overriding issue.
For example:

   use DB_File;;

   tie my %HASH, "DB_File", $file,
          O_CREAT|O_RDWR, 0666, $DB_HASH
      or die "error opening $file: $! ";

   my @valid_keys = ('foo ab', 'fooa b', ...  );  # valid keys

   foreach my $key (@some_keys) {
      $HASH{ $key } =  'new value'
                    if grep( $key eq $_, @valid_keys );
   }

--
Charles DeRykus





--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to