#!/usr/bin/perl use strict; use warnings; # get the list of file names -- actually, just make sure @ARGV has them: # declare a hash for output die "Usage: $0 *.txt > text.joined\n" unless ( @ARGV and -f $ARGV[0] ); my %output; # extra step: declare an array to preserve original order of keys in first file my @output_order; # open the first file # while reading each line from the file # get the first column of the line for use as a hash key # assign the line as the value of hash element using that key open( IN, '<', $ARGV[0] ) or die "Can't read $ARGV[0]: $!\n"; while () { my ( $key ) = ( /^(\S+)/ ); # extra steps: add key to order array, turn EOL whitespace into tab character push @output_order, $key; s/\s+$/\t/; $output{$key} = $_; } shift @ARGV; # (extra step: removes the file name that we just handled) # for each remaining file # open the file # while reading each line from the file # get the first column of the line for use as a hash key # append the line to the current value of the hash element using that key for my $file ( @ARGV ) { open( IN, '<', $file ) or die "Can't read $file: $!\n"; while () { my ( $key ) = ( /^(\S+)/ ); # extra step: turn EOL whitespace into a tab character s/\s+$/\t/; $output{$key} .= $_; } } # for each key in the hash -- using the original ordering # print the value of the hash element using that key for my $key ( @output_order ) { # extra step: convert the final tab character into a line-feed s/\t$/\n/; print $output{$key}; }