in reply to Can't access data stored in Hash - help!
Hello corcra, and welcome to the Monastery!
You begin by reading the whole of file 2, and saving all the data you will need later when processing file 1. This is inefficient, and may be problematic if file 2 is large. A better strategy is to read the two input files together, one line at a time:
#! perl use strict; use warnings; my $file1 = 'File1.txt'; my $file2 = 'File2.txt'; open(my $in1, '<', $file1) or die "Cannot open file '$file1' for reading: $!"; open(my $in2, '<', $file2) or die "Cannot open file '$file2' for reading: $!"; print scalar <$in1>; <$in2>; while (my $line1 = <$in1>) { my @fields1 = get_fields($line1); defined(my $line2 = <$in2>) or die "Data missing in file '$file2': $!"; my @fields2 = get_fields($line2); my @out = @fields1; for my $i (5 .. $#fields1) { if ($fields1[$i] ne 'REF' && $i <= $#fields2 && $fields2[$i] ne 'REF') { $out[$i] = $fields2[$i]; } } @out = map { "'$_'" } @out; print '[', join(', ', @out), "]\n"; } close $in2 or die "Cannot close file '$file2': $!"; close $in1 or die "Cannot close file '$file1': $!"; sub get_fields { my ($line) = @_; chomp $line; my @fields = split /\s*,\s*/, $line; s{ ^ \[? ' }{}x for @fields; s{ ' \]? $ }{}x for @fields; return @fields; }
Output:
13:39 >perl 959_SoPW.pl ['CHROM', 'POS', 'REF', 'ALT', 'LIST', 'SAMPLE_1A', 'SAMPLE_2A', 'SAMP +LE_3A'] ['M', '16', 'T', 'C', 'C', 'REF', 'C', 'REF'] ['M', '381', 'T', 'A', 'A', 'A', 'REF', 'REF'] ['M', '529', 'A', 'G', 'G', 'REF', 'G', 'REF'] 13:39 >
Note: In the above code I’ve assumed that the data files are formatted as you’ve shown. But if (as I half suspect) they are actually formatted as proper CSV files, then you will be better served reading them with one of the modules designed for this purpose, such as Text::CSV_XS.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can't access data stored in Hash - help!
by corcra (Initiate) on Aug 05, 2014 at 10:16 UTC | |
by Athanasius (Archbishop) on Aug 05, 2014 at 12:56 UTC | |
by corcra (Initiate) on Aug 10, 2014 at 14:46 UTC | |
by Athanasius (Archbishop) on Aug 11, 2014 at 13:58 UTC | |
by corcra (Initiate) on Aug 14, 2014 at 17:29 UTC |