On Jul 13, 5:42 pm, tiago.h...@gmail.com (Tiago Hori) wrote:
> ...
> >  C.DeRykus wrote:
> > There's already been a very good recommendation. But, if
> > you know your file has no irregularities, is surprise-free as
> > far as formatting,  you may be tempted to just try a 1-liner
> > since Perl does make "easy things easy...":
>
> > perl -lane 'if ($F[1] ne $old ) {open($fh,'>',$F[1]) or die $!};
> >                   print $fh $_;$old = $F[1]'   file

> I am trying to learn the CSV mode for the future, but this software will
> always spit the same file format at me, so your solution may be the way
> to go for now. Would you mi d giving me a quick explanation on what that
>  one liner does? It be useful for me to learn it in more depth and be to
> adapt it to future problems.

You're welcome.  As Jim says though, you're better off running a
multi-line program to learn basics if you're just beginning  and only
then trying a simpler solution.  Or, if you want to jump ahead, see
the doc (perldoc perlrun) to see what the switches mean.

Basically, the one-liner reads  the tab-delimited file line by line
(-n);  autosplits fields the line into fields based on whitespace (-
a)
and populates @F with those fields. If the 2nd column $F[1] ,
hasn't been seen or differs with the previous line's 2nd col.,
then a new output file is opened with a name matching $F[1].
The entire current line $_ is then written to the file. Lastly, $F[0]
is saved to $old so when the next line is read,  $F[0] can be
compared with $old to see if  a new file should be opened.

Note on switches:   -l          * unnecessary so can be omitted
                             -F\t       * could be added to split on
tab instead
                                            of whitespace

--
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to