Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Split tab-separated file into separate files, based on column name (updated)

by LanX (Saint)
on Aug 27, 2020 at 16:36 UTC ( [id://11121129]=note: print w/replies, xml ) Need Help??


in reply to Re: Split tab-separated file into separate files, based on column name
in thread Split tab-separated file into separate files, based on column name

ACHTUNG

The following code is buggy, sorry.

... it will create empty files for each field ...

D:\tmp>type 1,George,CEO 1 George CEO D:\tmp>

strange behavior... (Update: see solution here )


I didn't expect this, but Perl seems to silently refuse to re-open an already open file handle

so if you don't mind having the column head included you can go even shorter

D:\tmp>del id,name,position D:\tmp>perl -lanE "open $FH[$x++], '>', $_ for @F;print $_ shift @F f +or @FH" data.txt D:\tmp>type id,name,position id id 1 2 3 name name Nick George Christina position position boss CEO CTO D:\tmp>

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^3: Split tab-separated file into separate files, based on column name (updated)
by jcb (Parson) on Aug 28, 2020 at 01:17 UTC

    Try changing '>' to '>>'. If I remember correctly, open will silently reopen an already open handle. Since you are using truncating write mode, each file gets truncated every time it is opened.

      Hi

      The strange thing is that the "reopened" files are created but all output still goes to the first one.

      Probably a Windows issue...

      Ok got it. I'm pushing new file handles onto the @FH array, but only the first 3 ones are written!

      The trouble with overly clever one liners... 🤦🏻‍♂️

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

        Try putting open ..., '>', $_ for split scalar <> or similar in a BEGIN block, instead of running it on each loop iteration. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121129]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-16 21:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found