in reply to subset extraction from master file

One way to do it without file slurping:

use strict; use warnings; open MASTER, "file1" or die "cant't open master file: $!\n"; open SUBSET, "file2" or die "can't open subset file: $!\n"; open OUT, ">outfile" or die "can't open output file: $!\n"; while ( my $sline = <SUBSET> ) { chomp $sline; my ( $subkey, $subvals ) = split /:/, $sline, 2; my ( $mkey, $mvals ); while ( my $mline = <MASTER> ) { chomp $mline; ( $mkey, $mvals ) = split /:/, $mline, 2; last if $mkey eq $subkey; } print OUT join( ":", $subkey, $subvals, $mvals ), "\n"; } close SUBSET; close MASTER; close OUT or die "couldn't close outfile: $!\n";

The above snippet makes the assumption that the master file and the subset file are in the same order, and that every key in subset has an equal key in the master set (which is pretty much what you said). If the master file and the subset file are not in the same order, this method would need to be reworked, since synchronization is critical for its success.


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: subset extraction from master file
by tux242 (Acolyte) on Nov 18, 2003 at 16:30 UTC

    this gives me an error David like it does not understand what is trying to be opened? Below is the error:

    ./23file.pm: open: not found ./23file.pm: open: not found ./23file.pm: open: not found ./23file.pm: syntax error at line 4: `)' unexpected
    any clues? Thanks.

    Here is the code I am using

    open MASTER, "file3" or die "cant't open master file: $!\n"; open SUBSET, "file2" or die "can't open subset file: $!\n"; open OUT, ">outfile" or die "can't open output file: $!\n"; while ( my $sline = <SUBSET> ) { chomp $sline; my ( $subkey, $subvals ) = split /:/, $sline, 2; my ( $mkey, $mvals ); while ( my $mline = <MASTER> ) { chomp $mline; ( $mkey, $mvals ) = split /:/, $mline, 2; last if $mkey eq $subkey; } print OUT join ":", $subkey, $subvals, $mvals; } close SUBSET; close MASTER; close OUT or die "couldn't close outfile: $!\n";
      Sounds like you're executing the script as though it were a shell script rather than as a Perl script. Did you add a shebang line?

      Also, see my minor update to the "print" line.


      Dave


      "If I had my life to live over again, I'd be a plumber." -- Albert Einstein