Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
XP is just a number
 
PerlMonks  

Split and join - semicolons around empty fields are lost

by Anonymous Monk
on Sep 06, 2011 at 07:17 UTC ( #924326=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I process a semicolon separated file. In doing so I use  my @parts = split(/;/,$_); then I process some fields and then use  join (";",@parts) to get it together. In the file there are some empty fields at the end of the lines. In fact the last column ist e.g. always empty (except of the header). The semicolons at the end of the line are lost through split and join. How could I prevent it? Many thanks! VE

Comment on Split and join - semicolons around empty fields are lost
Select or Download Code
Re: Split and join - semicolons around empty fields are lost
by Corion (Pope) on Sep 06, 2011 at 07:20 UTC

    That's how split is documented. I really recommend that you use Text::CSV_XS, or at least pass in the number of expected columns to split.

Re: Split and join - semicolons around empty fields are lost
by Tux (Monsignor) on Sep 06, 2011 at 07:56 UTC

    That is the correct and documented behavior (perldoc -f split). Trailing empty fields are dropped on split when you use it like that. If you want to keep them, use:

    my @row = split m/;/ => $_, -1;

    As corion said, safer to use Text::CSV_XS.


    Enjoy, Have FUN! H.Merijn
Re: Split and join - semicolons around empty fields are lost
by Anonymous Monk on Sep 06, 2011 at 08:21 UTC
    Thank you very much!
    It works now both with "-1" and with the explicit number of columns (it was my first reaction after the post of corion - one can get the number of columns from the header line).
    I will certainly remake the script with Text_CSV, but now it was an emergency case and I am very glad to get the way around.
    Thanks again! VE

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://924326]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (11)
As of 2014-04-19 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (478 votes), past polls