Greetings perl monks,

Today my dilemma is reorganizing files. I actually have both a problem and a question. Say I'm starting with 2 files R1 and R2, as follows:
R1-something.txt R2-something.txt DESCRP a DESCRP a 2 3 3 1 DESCRP b DESCRP c 3 5 4 9
and I want to rearrange them so instead I have files
a.txt b.txt c.txt R1a R1b R2c 2 3 5 3 4 9 R2a 3 1
I have the files R1, R2 stored in fileArray and I think this should output them the way I would like:
foreach my $file (@{$fileArray}) { open (INPUT, "< $file") || die "Could not open $file\n"; while (<INPUT>) { if ($_ =~ /^DESCRP/) { #get name of element chomp (my $newFileName = substr($_, 7)); #open/create file of that name open OUTPUT, ">> $newFileName.txt" || die "Could not open +$_.txt\n"; #print the specific elements name print OUTPUT substr($file,0,2).$newFileName."txt\n"; } else { #or print the values following the element print OUTPUT $_; } } close OUTPUT; close INPUT; }

First, my problem is that when I try to print the values after each element, my OUTPUT handle is closed because it is out of scope from where I open it, and I am not sure how to keep it open.

My question is: Do you have a more efficient/aesthetic way of doing this?

Thanks for your time :)

-Thomas

P.S. the data sets I will actually be working with are much larger (1000s of lines and a dozen 'R_' files), but they will be generally like this.


In reply to Reorganizing file contents by tomdbs98

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.