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

Re: print last array element without a new line

by ikegami (Pope)
on Oct 19, 2011 at 19:32 UTC ( #932481=note: print w/replies, xml ) Need Help??

in reply to print last array element without a new line

Unless you're messing with $/ or $\, chomp will remove the newline, and there cannot possibly be two of them.

Your code does exactly what you say you want it to do.

while(<DATA>){ chomp(my $record = $_); my @field = split /\,/, $record; print "$field[0],$field[10],$values[0],$field[1],$field[2]\n"; } __DATA__ a,b,c,d,e,f,g,h,i,j,k a,b,c,d,e,f,g,h,i,j,k
a,k,,b,c a,k,,b,c

There's an empty field, but that's because I didn't give $values[0] a value. (In fact, I would get a warning with use warnings;.)

Replies are listed 'Best First'.
Re^2: print last array element without a new line
by sy (Initiate) on Oct 19, 2011 at 19:50 UTC
    Thanks for the check. And yet the code does NOT work. Against all expectation I continually get a new line after printing the last element of the array created by the split. I cannot find any explanation for why this might be occurring in any of my Perl books. I have read about $/ and $\ and checked through my code to ensure I didn't introduce some such change by a typo. So I'm left wondering how to solve the problem??? Anyone? The broader context may provide some hints: -the CSV files originate from LABVIEW -arrays of hashes are being used as a lookup table to link info from separate files. I'm tearing my hair out.
      Look at

        That means you had a carriage return in the middle of the line.

        A better solution would be to change

        chomp(my $record = $_);
        s/\r?\n//; my $record = $_;
        or even
        s/\s+\z//; my $record = $_;
        Thank you kindly! That was it. One of my files was from a distinct source (CSV export from Apple Numbers) and hence had a different line separator. Changing the local definition of $/ fixed the problem. Thanks so much for your help!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://932481]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-05-23 04:03 GMT
Find Nodes?
    Voting Booth?