Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

If you don't want to read the files twice you need to think about your data structure and how you turn it into the desired output. Something like this should work, read the data into a temporary data structure with the file as a secondary key. Then process it to fill in the blanks at output time.

#!/usr/bin/perl use strict; use warnings; my @files = glob("file*.tab"); my %data; for my $file ( @files ) { open my $fh, '<', $file or die $!; while ( <$fh> ) { chomp; my @columns = split /\t/; die "_ERROR_ not 9 columns [ $_ ]\n" if @columns != 9; my $key = join( "\t", @columns[0..3] ); $data{$key}->{$file} = $columns[6]; } close $fh; } print join("\t", 'chr', 'fivep', 'threep', 'strand', @files), "\n"; for my $key ( keys %data ) { my ( $chr, $fivep, $threep, $strand ) = split /\t/, $key; next if ( $strand =~ /^0$/ ); my @output; for my $file ( @files ) { push @output, $data{$key}->{$file} // 0; } print join("\t", $chr, $fivep, $threep, "-", @output ), "\n"; }

I also cleaned up the code a little and added some whitespace around things as I find it makes it easier to read.


In reply to Re: open input files once by rnewsham
in thread open input files once by v15

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-19 01:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found