UPDATE: Changed reading from "DATA" to get data from a sub.
I have to write a protocol to a printer. The printer needs a string to print, so I use perls format processor.
This works fine, for the first time. But if I try to write the protocol twice, the printed data are not correct formatted.
An example of the code I tried in short:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use utf8;
my $a;
my $b;
my $c;
my $protocol;
my $h_protocol;
format F_TOP =
---------------------------
1 2 3 P: @
$%
---------------------------
.
format F_ENTRY =
@<<< @<<< @<<<
$a, $b, $c
.
print_protocol("-1-"); # First run
print_protocol("-2-"); # Second run - should gibe the same output
sub print_protocol {
my $run = shift;
print "$run\n";
# Open protocol string as filehandle
open $h_protocol, ">", \$protocol;
# Set format to protocol filehandle
select((select($h_protocol), # Filehandle
$~ = "F_ENTRY",
$^ = "F_TOP",
$= = 5 # Lines per page
)[0]);
# Write data in protocol "file"
my @data = split /\n/, get_data();
for (@data) {
($a, $b, $c) = split /;/;
write $h_protocol;
}
# close filehandle
close $h_protocol;
# Print the protocol (to STDOUT to test)
print $protocol;
# Delete protocol data
$protocol = "";
}
sub get_data {
return "abc;def;ghi\njkl;mno;pqr\nabc;def;ghi\njkl;mno;pqr\nqwe;eqw;weq";
}
The output I get is:
-1-
---------------------------
1 2 3 P: 1
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 2
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 3
---------------------------
qwe eqw weq
-2-
abc def ghi
jkl mno pqr
abc def ghi
jkl mno pqr
qwe eqw weq
So how can I reset the protocol handle / the protocol processor so that the data is printed correct.
-1-
---------------------------
1 2 3 P: 1
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 2
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 3
---------------------------
qwe eqw weq
-2-
---------------------------
1 2 3 P: 1
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 2
---------------------------
abc def ghi
jkl mno pqr
♀---------------------------
1 2 3 P: 3
---------------------------
qwe eqw weq
In real the printer is not "STDOUT", of course.