Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Dynamically create a format definition

by tariqahsan (Beadle)
on Dec 13, 2001 at 19:28 UTC ( #131631=perlquestion: print w/replies, xml ) Need Help??

tariqahsan has asked for the wisdom of the Perl Monks concerning the following question:

I have a situation where I don't know how many variables and their values I would need to put in report. I am thinking of using the FORMAT template. Would anybody could know if I could dynamically create a FORMAT definition?

Replies are listed 'Best First'.
Re: Dynamically create a format definition
by jmcnamara (Monsignor) on Dec 13, 2001 at 19:54 UTC

    Have a look at the formline function and the accumulator $^A.

    Here is a short, seasonal, example that centres the elements of an array on separate lines. The format is built dynamically.

    #!/usr/bin/perl -w use strict; my @a = qw(* *** ***** ******* ********* *); formline(('@'.('|'x72)."\n")x@a, @a); print $^A;

    --
    John.

Re: Dynamically creating a format definition?
by traveler (Parson) on Dec 13, 2001 at 20:58 UTC
    My second edition camel book shows how to do it. The critical points are: 1) put the output of the format statement into a variable, 2) eval that variable. Here is a piece of demonstration code. I have tried to make it readable, it is surely not the most compact version possible.
    $data = qw( aaa bbb ccc ); $fields = scalar @data; $data_fields = ""; map $data_fields .= '"' . $_ . '"', @data; $format = "format STDOUT = \n" . "@<<< " x $fields . "\n" . $data_fields . "\n"; . ".\n"; eval $format; write;
    HTH, --traveler
Re: Dynamically create a format definition
by zakb (Pilgrim) on Dec 13, 2001 at 19:43 UTC
    Use eval. See the camel p 126 or perlform.
Re: Dynamically create a format definition
by IlyaM (Parson) on Dec 13, 2001 at 20:28 UTC
    Here two functions I use myself in one my module:
    # formated output sub sformat { my $format = shift; local $^A = ''; formline($format, @_); return $^A; } # print line using some format specification sub fprint { my $format = shift; $self->print(sformat($format, @_)); }

    --
    Ilya Martynov (http://martynov.org/)

Re: Dynamically create a format definition
by traveler (Parson) on Dec 13, 2001 at 21:09 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://131631]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2022-11-29 18:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?