P
PerlFAQ Server
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
5.12: How can I write() into a string?
(contributed by brian d foy)
If you want to "write" into a string, you just have to <open> a
filehandle to a string, which Perl has been able to do since Perl 5.6:
open FH, '>', \my $string;
write( FH );
Since you want to be a good programmer, you probably want to use a
lexical filehandle, even though formats are designed to work with
bareword filehandles since the default format names take the filehandle
name. However, you can control this with some Perl special
per-filehandle variables: $^, which names the top-of-page format, and $~
which shows the line format. You have to change the default filehandle
to set these variables:
open my($fh), '>', \my $string;
{ # set per-filehandle variables
my $old_fh = select( $fh );
$~ = 'ANIMAL';
$^ = 'ANIMAL_TOP';
select( $old_fh );
}
format ANIMAL_TOP =
ID Type Name
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
5.12: How can I write() into a string?
(contributed by brian d foy)
If you want to "write" into a string, you just have to <open> a
filehandle to a string, which Perl has been able to do since Perl 5.6:
open FH, '>', \my $string;
write( FH );
Since you want to be a good programmer, you probably want to use a
lexical filehandle, even though formats are designed to work with
bareword filehandles since the default format names take the filehandle
name. However, you can control this with some Perl special
per-filehandle variables: $^, which names the top-of-page format, and $~
which shows the line format. You have to change the default filehandle
to set these variables:
open my($fh), '>', \my $string;
{ # set per-filehandle variables
my $old_fh = select( $fh );
$~ = 'ANIMAL';
$^ = 'ANIMAL_TOP';
select( $old_fh );
}
format ANIMAL_TOP =
ID Type Name