{
    "mode": "perldoc",
    "parameter": "Template::Tutorial::Datafile",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Template%3A%3ATutorial%3A%3ADatafile/json",
    "generated": "2026-06-10T20:31:05Z",
    "sections": {
        "NAME": {
            "content": "Template::Tutorial::Datafile - Creating Data Output Files Using the Template Toolkit\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "",
            "subsections": []
        },
        "Introducing the Template Toolkit": {
            "content": "There are a number of Perl modules that are universally recognised as The Right Thing To Use for\ncertain tasks. If you accessed a database without using DBI, pulled data from the WWW without\nusing one of the LWP modules or parsed XML without using XML::Parser or one of its subclasses\nthen you'd run the risk of being shunned by polite Perl society.\n\nI believe that the year 2000 saw the emergence of another 'must have' Perl module - the Template\nToolkit. I don't think I'm alone in this belief as the Template Toolkit won the 'Best New\nModule' award at the Perl Conference last summer. Version 2.0 of the Template Toolkit (known as\nTT2 to its friends) was recently released to the CPAN.\n\nTT2 was designed and written by Andy Wardley <abw@wardley.org>. It was born out of Andy's\nprevious templating module, Text::Metatext, in best Fred Brooks 'plan to throw one away' manner;\nand aims to be the most useful (or, at least, the most *used*) Perl templating system.\n\nTT2 provides a way to take a file of fixed boilerplate text (the template) and embed variable\ndata within it. One obvious use of this is in the creation of dynamic web pages and this is\nwhere a lot of the attention that TT2 has received has been focussed. In this article, I hope to\ndemonstrate that TT2 is just as useful in non-web applications.\n",
            "subsections": []
        },
        "Using the Template Toolkit": {
            "content": "Let's look at how we'd use TT2 to process a simple data file. TT2 is an object oriented Perl\nmodule. Having downloaded it from CPAN and installed it in the usual manner, using it in your\nprogram is as easy as putting the lines\n\nuse Template;\nmy $tt = Template->new;\n\nin your code. The constructor function, \"new\", takes a number of optional parameters which are\ndocumented in the copious manual pages that come with the module, but for the purposes of this\narticle we'll keep things as simple as possible.\n\nTo process the template, you would call the \"process\" method like this\n\n$tt->process('mytemplate', \\%data)\n|| die $tt->error;\n\nWe pass two parameters to \"process\", the first is the name of the file containing the template\nto process (in this case, mytemplate) and the second is a reference to a hash which contains\nthe data items that you want to use in the template. If processing the template gives any kind\nof error, the program will die with a (hopefully) useful error message.\n\nSo what kinds of things can go in %data? The answer is just about anything. Here's an example\nshowing data about English Premier League football teams.\n\nmy @teams = ({ name   => 'Man Utd',\nplayed => 16,\nwon    => 12,\ndrawn  => 3,\nlost   => 1 },\n{ name   => 'Bradford',\nplayed => 16,\nwon    => 2,\ndrawn  => 5,\nlost   => 9 });\n\nmy %data = ( name   => 'English Premier League',\nseason => '2000/01',\nteams  => \\@teams );\n\nThis creates three data items which can be accessed within the template, called \"name\", \"season\"\nand \"teams\". Notice that \"teams\" is a complex data structure.\n\nHere is a template that we might use to process this data.\n\nLeague Standings\n\nLeague Name: [% name %]\nSeason     : [% season %]\n\nTeams:\n[% FOREACH team = teams -%]\n[% team.name %] [% team.played -%]\n[% team.won %] [% team.drawn %] [% team.lost %]\n[% END %]\n\nRunning this template with this data gives us the following output\n\nLeague Standings\n\nLeague Name: English Premier League\nSeason     : 2000/01\n\nTeams:\nMan Utd 16 12 3 1\nBradford 16 2 5 9\n\nHopefully the syntax of the template is simple enough to follow. There are a few points to note.\n\n*   Template processing directives are written using a simple language which is not Perl.\n\n*   The keys of the %data have become the names of the data variables within the template.\n\n*   Template processing directives are surrounded by \"[%\" and \"%]\" sequences.\n\n*   If these tags are replaced with \"[%-\" \"-%]\" then the preceding or following linefeed is\nsuppressed.\n\n*   In the \"FOREACH\" loop, each element of the \"teams\" list was assigned, in turn, to the\ntemporary variable \"team\".\n\n*   Each item assigned to the \"team\" variable is a Perl hash. Individual values within the hash\nare accessed using a dot notation.\n\nIt's probably the first and last of these points which are the most important. The first point\nemphasises the separation of the data acquisition logic from the presentation logic. The person\ncreating the presentation template doesn't need to know Perl, they only need to know the data\nitems which will be passed into the template.\n\nThe last point demonstrates the way that TT2 protects the template designer from the\nimplementation of the data structures. The data objects passed to the template processor can be\nscalars, arrays, hashes, objects or even subroutines. The template processor will just interpret\nyour data correctly and Do The Right Thing to return the correct value to you. In this example\neach team was a hash, but in a larger system each team might be an object, in which case \"name\",\n\"played\", etc. would be accessor methods to the underlying object attributes. No changes would\nbe required to the template as the template processor would realise that it needed to call\nmethods rather than access hash values.\n\nA more complex example\nStats about the English Football League are usually presented in a slightly more complex format\nthan the one we used above. A full set of stats will show the number of games that a team has\nwon, lost or drawn, the number of goals scored for and against the team and the number of points\nthat the team therefore has. Teams gain three points for a win and one point for a draw. When\nteams have the same number of points they are separated by the goal difference, that is the\nnumber of goals the team has scored minus the number of team scored against them. To complicate\nthings even further, the games won, drawn and lost and the goals for and against are often split\nbetween home and away games.\n\nTherefore if you have a data source which lists the team name together with the games won, drawn\nand lost and the goals for and against split into home and away (a total of eleven data items)\nyou can calculate all of the other items (goal difference, points awarded and even position in\nthe league). Let's take such a file, but we'll only look at the top three teams. It will look\nsomething like this:\n\nMan Utd,7,1,0,26,4,5,2,1,15,6\nArsenal,7,1,0,17,4,2,3,3,7,9\nLeicester,4,3,1,10,8,4,2,2,7,4\n\nA simple script to read this data into an array of hashes will look something like this (I've\nsimplified the names of the data columns - w, d, and l are games won, drawn and lost and f and a\nare goals scored for and against; h and a at the front of a data item name indicates whether\nit's a home or away statistic):\n\nmy @cols = qw(name hw hd hl hf ha aw ad al af aa);\n\nmy @teams;\nwhile (<>) {\nchomp;\n\nmy %team;\n\n@team{@cols} = split /,/;\n\npush @teams, \\%team;\n}\n\nWe can then go thru the teams again and calculate all of the derived data items:\n\nforeach (@teams) {\n$->{w} = $->{hw} + $->{aw};\n$->{d} = $->{hd} + $->{ad};\n$->{l} = $->{hl} + $->{al};\n\n$->{pl} = $->{w} + $->{d} + $->{l};\n\n$->{f} = $->{hf} + $->{af};\n$->{a} = $->{ha} + $->{aa};\n\n$->{gd} = $->{f} - $->{a};\n$->{pt} = (3 * $->{w}) + $->{d};\n}\n\nAnd then produce a list sorted in descending order:\n\n@teams = sort {\n$b->{pt} <=> $b->{pt} || $b->{gd} <=> $a->{gd}\n} @teams;\n\nAnd finally add the league position data item:\n\n$teams[$]->{pos} = $ + 1\nforeach 0 .. $#teams;\n\nHaving pulled all of our data into an internal data structure we can start to produce output\nusing out templates. A template to create a CSV file containing the data split between home and\naway stats would look like this:\n\n[% FOREACH team = teams -%]\n[% team.pos %],[% team.name %],[% team.pl %],[% team.hw %],\n[%- team.hd %],[% team.hl %],[% team.hf %],[% team.ha %],\n[%- team.aw %],[% team.ad %],[% team.al %],[% team.af %],\n[%- team.aa %],[% team.gd %],[% team.pt %]\n[%- END %]\n\nAnd processing it like this:\n\n$tt->process('split.tt', { teams => \\@teams }, 'split.csv')\n|| die $tt->error;\n\nproduces the following output:\n\n1,Man Utd,16,7,1,0,26,4,5,2,1,15,6,31,39\n2,Arsenal,16,7,1,0,17,4,2,3,3,7,9,11,31\n3,Leicester,16,4,3,1,10,8,4,2,2,7,4,5,29\n\nNotice that we've introduced the third parameter to \"process\". If this parameter is missing then\nthe TT2 sends its output to \"STDOUT\". If this parameter is a scalar then it is taken as the name\nof a file to write the output to. This parameter can also be (amongst other things) a filehandle\nor a reference to an object which is assumed to implement a \"print\" method.\n\nIf we weren't interested in the split between home and away games, then we could use a simpler\ntemplate like this:\n\n[% FOREACH team = teams -%]\n[% team.pos %],[% team.name %],[% team.pl %],[% team.w %],\n[%- team.d %],[% team.l %],[% team.f %],[% team.a %],\n[%- team.aa %],[% team.gd %],[% team.pt %]\n[% END -%]\n\nWhich would produce output like this:\n\n1,Man Utd,16,12,3,1,41,10,6,31,39\n2,Arsenal,16,9,4,3,24,13,9,11,31\n3,Leicester,16,8,5,3,17,12,4,5,29\n",
            "subsections": []
        },
        "Producing XML": {
            "content": "This is starting to show some of the power and flexibility of TT2, but you may be thinking that\nyou could just as easily produce this output with a \"foreach\" loop and a couple of \"print\"\nstatements in your code. This is, of course, true; but that's because I've chosen a deliberately\nsimple example to explain the concepts. What if we wanted to produce an XML file containing the\ndata? And what if (as I mentioned earlier) the league data was held in an object? The code would\nthen look even easier as most of the code we've written earlier would be hidden away in\n\"FootballLeague.pm\".\n\nuse FootballLeague;\nuse Template;\n\nmy $league = FootballLeague->new(name => 'English Premier');\n\nmy $tt = Template->new;\n\n$tt->process('leaguexml.tt', { league => $league })\n|| die $tt->error;\n\nAnd the template in \"leaguexml.tt\" would look something like this:\n\n<?xml version=\"1.0\"?>\n<!DOCTYPE LEAGUE SYSTEM \"league.dtd\">\n\n<league name=\"[% league.name %]\" season=\"[% league.season %]\">\n[% FOREACH team = league.teams -%]\n<team name=\"[% team.name %]\"\npos=\"[% team.pos %]\"\nplayed=\"[% team.pl %]\"\ngoaldiff=\"[% team.gd %]\"\npoints=\"[% team.pt %]\">\n<stats type=\"home\">\nwin=\"[% team.hw %]\"\ndraw=\"[%- team.hd %]\"\nlose=\"[% team.hl %]\"\nfor=\"[% team.hf %]\"\nagainst=\"[% team.ha %]\" />\n<stats type=\"away\">\nwin=\"[% team.aw %]\"\ndraw=\"[%- team.ad %]\"\nlose=\"[% team.al %]\"\nfor=\"[% team.af %]\"\nagainst=\"[% team.aa %]\" />\n</team>\n[% END -%]\n&/league>\n\nNotice that as we've passed the whole object into \"process\" then we need to put an extra level\nof indirection on our template variables - everything is now a component of the \"league\"\nvariable. Other than that, everything in the template is very similar to what we've used before.\nPresumably now \"team.name\" calls an accessor function rather than carrying out a hash lookup,\nbut all of this is transparent to our template designer.\n",
            "subsections": []
        },
        "Multiple Formats": {
            "content": "As a final example, let's suppose that we need to create output football league tables in a\nnumber of formats. Perhaps we are passing this data on to other people and they can't all use\nthe same format. Some of our users need CSV files and others need XML. Some require data split\nbetween home and away matches and other just want the totals. In total, then, we'll need four\ndifferent templates, but the good news is that they can use the same data object. All the script\nneeds to do is to establish which template is required and process it.\n\nuse FootballLeague;\nuse Template;\n\nmy ($name, $type, $stats) = @;\n\nmy $league = FootballLeague->new(name => $name);\n\nmy $tt = Template->new;\n\n$tt->process(\"league${type}$stats.tt\",\n{ league => $league }\n\"league$stats.$type\")\n|| die $tt->error;\n\nFor example, you can call this script as\n\nleague.pl 'English Premier' xml split\n\nThis will process a template called \"leaguexmlsplit.tt\" and put the results in a file called\n\"leaguesplit.xml\".\n\nThis starts to show the true strength of the Template Toolkit. If we later wanted to add another\nfile format - perhaps we wanted to create a league table HTML page or even a LaTeX document -\nthen we would just need to create the appropriate template and name it according to our existing\nnaming convention. We would need to make no changes to the code.\n\nI hope you can now see why the Template Toolkit is fast becoming an essential part of many\npeople's Perl installation.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Dave Cross <dave@dave.org.uk>\n",
            "subsections": []
        },
        "VERSION": {
            "content": "Template Toolkit version 2.19, released on 27 April 2007.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (C) 2001 Dave Cross <dave@dave.org.uk>\n\nThis module is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "Template::Tutorial::Datafile - Creating Data Output Files Using the Template Toolkit",
    "flags": [],
    "examples": [],
    "see_also": []
}