Tweet

How do I remove a newline from the end of a string?

You have a variable in your program (perhaps containing some text that you've read in from a file), that has a newline at the end of it.

The problem code

    #!/usr/bin/perl
    use strict;
    use warnings;

    while (<>) {
        my $var = $_;
        print "I read: " . $var . "from the file\n";
    }

...which gives you this output...

    I read: 12345
    from the file

...but you want to see...

    I read: 12345 from the file

The solution

The chomp function removes the input record separator from the end of a string.

    #!/usr/bin/perl
    use strict;
    use warnings;

    while (<>) {
        my $var = $_;
        chomp $var;
        print "I read: " . $var . "from the file\n";
    }

See also

    perldoc -f chomp
    perldoc perlvar (see the entry for $/)
[Top]