1

I'm trying to use chomp() to remove all the newline character from a file. Here's the code:

    use strict;
    use warnings;

    open (INPUT, 'input.txt') or die "Couldn't open file, $!";
    my @emails = <INPUT>;
    close INPUT;

    chomp(@emails);

    my $test;
    foreach(@emails)
    {
      $test = $test.$_;
    }

    print $test;

and the test conent for the input.txt file is simple:

    hello.com
    hello2.com
    hello3.com
    hello4.com

my expected output is something like this: hello.comhello2.comhello3.comhello4.com

however, I'm still getting the same content as the input file, any help please?

Thank you

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
shensw
  • 223
  • 1
  • 3
  • 14
  • You're chomping one big string. – Maria Ines Parnisari Jan 24 '14 at 04:17
  • isn't chomp(@emails) chomping a list? – shensw Jan 24 '14 at 04:19
  • Yes, you're chomping each element in the list. And it works as you expected for me. – ooga Jan 24 '14 at 04:23
  • @shensw: yes, it's doing a chomp on each element of the array. what is `$/` variable set to? that's the character that chomp removes. if it's DOS format file, each line is going to have CR and LF (CHR(13) and CHR(10) characters... you can run dos2unix on the file... – spencer7593 Jan 24 '14 at 04:24
  • I am getting the output that you said you would expect. If you use something like Data::Dumper to print your data structure you can see an indication of newline or the lack of one. – BryanK Jan 24 '14 at 04:25
  • I see, that could be the case. I'm actually testing it on the online interpreter from here: http://www.compileonline.com/execute_perl_online.php THANKS, guys – shensw Jan 24 '14 at 04:29
  • note that the code you show will give a `Use of uninitialized value $test in concatenation (.) or string` warning; use `$test .= $_;` instead. (Though even then, if the file is empty, the `print $test;` will give a warning, so you probably want to `my $test = '';` initially.) – ysth Jan 24 '14 at 06:21

1 Answers1

6

If the input file was generated on a different platform (one that uses a different EOL sequence), chomp might not strip off all the newline characters. For example, if you created the text file in Windows (which uses \r\n) and ran the script on Mac or Linux, only the \n would get chomp()ed and the output would still "look" like it had newlines.

If you know what the EOL sequence of the input is, you can set $/ before chomp(). Otherwise, you may need to do something like

my @emails = map { s/[\n\r]+$//g; $_ } <INPUT>;
mojo
  • 4,050
  • 17
  • 24