CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [S3] Perl or simple Lample:inux commands for joining information in two files?: Edit Log



Kenosis
User

Mar 25, 2013, 2:06 PM


Views: 693
Re: [S3] Perl or simple Lample:inux commands for joining information in two files?

Your dataset description was helpful.

If I understand you correctly, you want to match the files' unique name entires, and then combine some of their fields, printing them as a tab-delimited record.

If so, I'd read in t.txt first, and create a hash with each key as a unique name and the statistical number as its associated value. Then, iterate through a.txt, to match its unique name with a key, then format and print a line when found.

Given this, consider the following:


Code
use strict; 
use warnings;

# Declare a hash
my %hash;

# Take the first file name (a.txt) off @ARGV
my $a_text = shift;

# Read t.txt line-by-line; $_ (the default scalar) contains each line
while (<>) {
# Split the line on whitespace
if ( my @name_num = split ) {
$hash{ $name_num[0] } = $name_num[1];
}
}

# Place "a.txt" back into @ARGV
push @ARGV, $a_text;

# Read a.txt line-by-line
while (<>) {
if ( my @record = split ) {
# If the files' unique names match, print a record
print "$record[2]\t$hash{$record[2]}\t$record[0]\t$record[1]\n"
if $hash{ $record[2] };
}
}


Usage: perl script.pl a.txt t.txt >results.txt (These file names are placed into @ARGV)

The script first saves the first file's name for later, then reads through t.txt, populating a hash with key/value pairs. It restores the first file's name to @ARGV and then reads through it, splitting each line and printing a record if it finds a matching unique name in the hash from a.txt.

Hope this helps!


(This post was edited by Kenosis on Mar 26, 2013, 9:28 AM)


Edit Log:
Post edited by Kenosis (User) on Mar 26, 2013, 9:27 AM
Post edited by Kenosis (User) on Mar 26, 2013, 9:28 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives