arrays - Perl, reading text files, saving columns for using elements of columns to open other files -


i have text file, tab separated, follows:

< header

col1 col2 col3
blablabla text1.txt blablabla
blablabla text2.txt blablabla
blablabla text3.txt blablabla

i want able extract elements (columns), in case words text1.txt, text2.txt , text3.txt. want use them later open files names. far have code:

#!/usr/bin/perl use strict; use warnings;  @fields; ($column1, $column2, $column3);  $text = "text.txt";  open(file, $text) or die "could not read $text, program halting.";  @files;  while(<file>) {   chomp;    /^</ , next;    /^\s*$/ , next;    /line*/ , next;    ($column1, $column2, $column3) = split('\s', $_);  #print 1 #print $column2, "\t";   } #print 2 print $column2, "\t";  close file; 

if print commented #print one, correct version output only,with 3 elements when try save in variable or write file, "text3.txt" remains. if print in #print two, 1 element, same text3.txt. how learn this? have tried lots of codes site no result far.thank you.

this happening because overwrite $column2 on every pass of loop, after leave loop, have last result (text3.txt).

you can write file within loop, example shows. shows how use proper 3-arg open, lexical file handles:

use warnings; use strict;  $input_file = 'data.txt'; $output_file = 'out.txt';  open $fh, '<', $input_file or die $!; open $wfh, '>', $output_file or die $!;  while (<$fh>){     chomp;     next if /^\</;     next if /^\s*$/;      ($c1, $c2, $c3) = split /\s/, $_;      print $wfh "$c2\n"; } 

given input file:

< header  col1 col2 col3 blablabla text1.txt blablabla blablabla text2.txt blablabla blablabla text3.txt blablabla 

produces:

col2 text1.txt text2.txt text3.txt 

...in output file. you'll have sort out how filter first line.

you can save output array within loop, work on later:

use warnings; use strict;  $input_file = 'data.txt';  open $fh, '<', $input_file or die $!;  @saved_entries;  while (<$fh>){     chomp;     next if /^\</;     next if /^\s*$/;     push @saved_entries, (split /\s/, $_)[1]; }  (@saved_entries){     print "$_\n"; } 

...which can write file or need with.

note i'm being overly verbose here, as close op code possible.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -