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

Greetings Monks,
I'm new to perl, and I've been looking at working example of how I may utilise Perl format to style my output in a certain manner. Many of these examples show that this reporting feature is based around the filehandler, problem is i'm pulling stuff out of arrays. I'm kindna clueless on how should I go about this. Any advise is appreciated. Thank you.

for example

sub test{ foreach my $stuffs (@{$object->{'school'}}) { print "Student Name: $item->{'sname'}\n" ; print "class: $item->{'class'}\n\n"; print "enrolled Date: $item->{'EnrolDate'}\n\n"; print "class id: $item->{'classid'}\n\n"; } }

Instead of using print, I want to use format. In this case, how should I use format? is the format name test? which variables should I use for the format pictures?

Replies are listed 'Best First'.
Re: Perl Format on arrays
by cdarke (Prior) on Apr 18, 2011 at 09:43 UTC
    Formats are named after the file handle you are writing to. For example:
    sub testf { my $object = shift; my ($sname,$class,$date,$classid); foreach my $item (@{$object->{'school'}}) { $sname = $item->{'sname'}; $class = $item->{'class'}; $date = $item->{'EnrolDate'}; $classid = $item->{'classid'}; write STDOUT } format STDOUT = Student Name @<<<<<<<<<<<<<<<< $sname Class: @>>>>>>>>>>>> $class Enrolled Date: @||||||| $date Class id.: @||||||||| $classid . } my $object = {school => [ {sname => 'Asname', class => 'Aclass', EnrolDate => '10/10/66', classid => 'Perl'}, {sname => 'Bsname', class => 'Bclass', EnrolDate => '10/10/66', classid => 'Perl'}, {sname => 'Csname', class => 'Cclass', EnrolDate => '10/10/66', classid => 'Perl'} ]}; testf($object);
    Gives:
    Student Name Asname Class: Aclass Enrolled Date: 10/10/66 Class id.: Perl Student Name Bsname Class: Bclass Enrolled Date: 10/10/66 Class id.: Perl Student Name Csname Class: Cclass Enrolled Date: 10/10/66 Class id.: Perl
    Personally I find printf simpler.

    Update: Added blank line to break-up each record. Also note that the format cannot be indented, even though it is in a subroutine.
      +1 on using printf instead
Re: Perl Format on arrays
by jethro (Monsignor) on Apr 18, 2011 at 09:40 UTC

    You declare the format you want with 'format'. You print the data with 'write'. i.e. to print out each sname and class you would use

    write($item->{'sname'}, $item->{'class'});

    UPDATE: The example is wrong. See cdarkes example how it is done

    A small hint: Try first with a very simple format and only one variable (maybe copy an example from the perl documentation), then built up to what you want in small steps and test your script inbetween whether it still works. If it doesn't work anymore you know exactly which change produced the wrong result and can retrace your steps and try something else or correct it