Question

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

Was it helpful?

Solution

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>;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top