Advertisement
hakonhagland

reduce

Feb 15th, 2021
1,570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.73 KB | None | 0 0
  1. use feature qw(say);
  2. use strict;
  3. use warnings;
  4.  
  5. {
  6.     my @names;  # keeps the same order of the lines
  7.     my %lines;  # names and numbers
  8.  
  9.     read_file('file1', \@names, \%lines);
  10.     read_file('file2', \@names, \%lines);
  11.     for my $name (@names) {
  12.         say $name, " ", join " ", @{$lines{$name}};
  13.     }
  14. }
  15.  
  16. sub read_file {
  17.     my ( $fn, $names, $lines ) = @_;
  18.     open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
  19.     while( my $line = <$fh> ) {
  20.         chomp $line;
  21.         next if $line !~ /\S/;  # skip empty lines
  22.         my ( $name, $number ) = $line =~ /^(.*)\s+(\d+)\s*$/;
  23.         push @$names, $name if !exists $lines->{$name};
  24.         push @{$lines->{$name}}, $number;
  25.     }
  26.     close $fh;
  27. }
  28.  
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement