I found this solution in Perl interesting. I have a similar situation to print matching columns and two additional columns from the second file (Rev ID n date released). How do I read both files from this code. I am planning to dissect this code and learn hashing and arrays from this.


# create names lookup table from first file
  my %names;
  while (<>) {
  (my $col1)= split / /, $_;
  $names{$col1} = 1;
  last if eof;

# scan second file
  while (<>) {
  print if /^(\S+).*/ && not $names{$1};

 File 1:
 Name               IRR ID
 slic73p1hsicbxttop 99034438
 c73p1avrfusevrmtop 99034201

 Example file 2
 Type Name              Rev ID   IRR ID   PP Group      Date Released  PP Category                              
 Comp c73p1avrfusevrmtop PROD_2_5 99034201 SEG RIP Reuse 5/3/2015 6:59   Hard   
 Comp c73p1avrfusevrmtop PROD_2_4 99034201 SEG RIP Reuse 4/23/2015 10:27 Hard   
 Comp c73p1avrfusevrmtop PROD_2_3 99034201 SEG RIP Reuse 3/17/2015 23:51 Hard   
 Comp c73p1avrfusevrmtop PROD_2_2 99034201 SEG RIP Reuse 2/1/2015 11:27  Hard   

 Expected Output: there are also other rows in the table which doesn't match
 IRR ID   Rev ID   Date Released (date to be printed in a chronological   order)
 99034201 PROD_2_5 5/3/2015 6:59    
 99034201 PROD_2_4 4/23/2015 10:27  
 99034201 PROD_2_3 3/17/2015 23:51  
 99034201 PROD_2_2 2/1/2015 11:27  

First chunk:

my %names;
while (<>) {
    ( my $col1 ) = split / /, $_;
    $names{$col1} = 1;
    last if eof;
  • We declare a hash called names.
  • We cycle through a filehandle, one line at a time. This file handle is <> which has a special meaning in perl - it's either STDIN or the contents of the files specified on the command line. It looks like this code only works in the latter case, which is generally bad form.
  • In each loop iteration, $_ is set to the current line.
  • $_ is split on whitespace, which turns it into an array.
  • my ( $col1 ) is an array - the first element out of the split is assigned to $col1. (You could assign the rest with my ( $col1, $col2, @more_cols ) = ... )
  • The key $col1 in the names hash is set to 1.


$VAR1 = {
          'c73p1avrsrldo150top' => 1,
          'c73p1avrfusevrmtop' => 1,
          'slic73p1hsicbxttop' => 1

Then we start on the second file:

  while (<>) {
      print if /^(\S+).*/ && not $names{$1};

Starts with a bad regular expression that 'just' captures the first word on the line (into $1). And if $names{$1} isn't set, will print the line.

Which given your input data is simply not going to work - because you're checking if Comp is present in names and it won't be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.