Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: How to approach this problem, or should I ignore it?

by rubasov (Friar)
on Apr 07, 2010 at 21:04 UTC ( #833395=note: print w/replies, xml ) Need Help??

in reply to How to approach this problem, or should I ignore it?

Here's my stab at it:
#! /usr/bin/perl use strict; use warnings; use Text::Template; use List::MoreUtils qw( natatime ); my %cmd_data = ( ... ); our $max_sf_cols = 5; my $template = Text::Template->new( TYPE => 'FILEHANDLE', SOURCE => \* +DATA ) or die "Couldn't construct template: $Text::Template::ERROR"; for my $cmd ( sort keys %cmd_data ) { local our $opcode = $cmd_data{$cmd}{opcode}; my @sf_names; push @sf_names, $_->{subfield_name} for @{ $cmd_data{$cmd}{subfields} }; @sf_names = qw( none ) if not @sf_names; my $it = natatime $max_sf_cols, @sf_names; print $template->fill_in() while local our @sf_cols = $it->(); } __DATA__ <p> <table border="1"> <thead> <tr> <th>opcode</th> <th colspan="{ $max_sf_cols }" align="center">subfield(s)</th> </tr> </thead> <tbody> <tr> <td>{ $opcode }</td> { $OUT .= "<td>$_</td>" for @sf_cols } </tr> </tbody> </table> </p>

Probably the most interesting part of it is the List::MoreUtils::natatime (n at a time) function. This almost does the same as jethro's splice, but without changing your data structure. It gives you an iterator sub, and every time you call that iterator sub it gives you the next five items from an array. You can use this in your existing code without bothering much with the other parts.

The templating is just an extra. You can see the template in the DATA section, where every { perl code } section will be replaced by the value of its last statement, or with the value of $OUT if you appended something to it. Notice the scoping of the variables used both in the template and in the main code. They are not lexicals, because you cannot see lexicals of the main code in the templating code fragments.

I'm not dealing much with HTML templating, so I'm sure there are better ways to do this, but I hope this helps.

Replies are listed 'Best First'.
Re^2: How to approach this problem, or should I ignore it?
by jedikaiti (Hermit) on Apr 08, 2010 at 16:20 UTC

    Excellent! Many thanks, rubasov!

    Swiss Army Nerd

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://833395]
Discipulus I'd rather say good weak start..

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2018-05-28 08:17 GMT
Find Nodes?
    Voting Booth?