Perl file handles on strings and formatted output
Perl reads and writes files through file handles. open(my $in, '<', $path) opens a file for reading, and the diamond operator <$in> reads one line at a time. If the file name is replaced by a reference to a string, \$data, the same code reads from or writes to that string in memory. That is handy for testing code that normally uses files, and it works the same way everywhere.
Perl
use strict;
use warnings;
my $data = "alpha 3\nbeta 5\ngamma x\n";
open(my $in, '<', \$data) or die "cannot open: $!";
my $total = 0;
while (my $line = <$in>) {
chomp $line;
my ($name, $value) = split ' ', $line;
if ($value =~ /^\d+$/) {
print "$name=$value\n";
$total += $value;
} else {
print "bad line: $line\n";
}
}
close $in;
print "total $total\n";
my $report = '';
open(my $out, '>', \$report) or die "cannot open: $!";
printf $out "%-6s|%3d\n", "ab", 7;
print {$out} "done\n";
close $out;
print $report;