http://www.perlmonks.org?node_id=924326

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

Replies are listed 'Best First'.
Re: Split and join - semicolons around empty fields are lost
by Corion (Patriarch) 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 (Canon) 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