1

I have this script

open (DICT,'file 0 .csv'); 

my @dictio = <DICT>;
chomp @dictio;
print @dictio;

My file 0 .csv is like this :

AAAA , a
AAAT , b
AAAC , c

So using chomp I want to delete the new row character, but when I print it my array dissapear. And when I print my array without using chomp it prints like the initially file.

So what am I doing wrong with the command chomp?

Thanks

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
crocket
  • 37
  • 4
  • The only error you might get from this would be `readline() on closed filehandle`, in case the `open` failed. Is your file really named `"file 0 .csv`, including the spaces? Also, `chomp` only removes the value of `$/` (newline by default), so it should not affect the other characters in the array. – TLP Nov 05 '13 at 10:41
  • 2
    Also, it sounds like you might be having a line endings problem, which is the result of using `chomp` on a file with CRLF line endings. E.g. if a line is `foo\r\n` it will be `foo\r` after `chomp`, which means any subsequent lines will overwrite `foo` on the terminal. – TLP Nov 05 '13 at 10:45
  • I agree with TLP (in the second comment). To rectify, you should set the value of $/ to "\r\n" (since I'm guessing you're on a *nix box and it's default value is "\n") – Tim Peoples Nov 05 '13 at 12:05

2 Answers2

0

Try this

open (my $DICT, '<', 'file 0 .csv') or die "cannot open file "; 

my @dictio = <$DICT>;
chomp @dictio;
print @dictio;
mpapec
  • 50,217
  • 8
  • 67
  • 127
Noble
  • 77
  • 7
  • 3
    Try what? Using the explicit open mode and a lexical file handle? That would make no difference, but changing the file name to `0.csv` might. Perhaps you should provide an explanation with your answer. Strangely, the OP accepted this answer, despite having (indirectly) said he had no problem opening the file. – TLP Nov 05 '13 at 10:37
  • @TLP I had similar problem as OP, using || to print any error message by open did not help. Turned our the file had CRLF endings. After fixing it, the error disappeared, but I dont know why. – user13107 Jun 26 '14 at 23:06
0
open (my $DICT, '<', 'file 0 .csv') or die "cannot open file ";
while ( my $line = <$DICT> ) {
    chomp $line;
    my @line = split( ',' , $line );
}
close($DICT);

Your current code reads in the entire file into an array. I think it's slurping when done this way. As a result, your chomp is not performing as you would expect. Chomp is usually used with a scalar variable, as i've used it above, to chop off the '\n' in each line.

The code i've written above reads your file line-by-line into an array i've chosen to call @line, which contains each field of the current line of your file. This allows you to process one line at a time.