Perl - Append to last line of a file (onto same line)

append, perl

Solution

Assuming the last line has no newline

use strict;
use warnings;

open(my $fd, ">>file.txt");
print $fd " 20";

If the last line already has a newline, the output will end up on the next line, i.e.

a b c d 10
 20

A longer version working in either case would be

use strict;
use warnings;

open(my $fd, "file.txt");
my $previous;
while (<$fd>) {
    print $previous if ($previous);
    $previous = $_;
}

chomp($previous);
print "$previous 20\n";

However, this version doesn't modify the original file.

Problem

Can someone let me know how to append an output file's last entry based on the current value? E.g. I am generating an output `.txt` file, say: ``` a b c d 10 ``` With some processing I get value `20` and now I want that value to be assigned and aligned with previous set, making it: ``` a b c d 10 20 ```

Original source