{
    "content": [
        {
            "type": "text",
            "text": "# Template::Manual::VMethods (perldoc)\n\n## NAME\n\nTemplate::Manual::VMethods - Virtual Methods\n\n## Sections\n\n- **NAME**\n- **Scalar Virtual Methods**\n- **Hash Virtual Methods**\n- **List Virtual Methods**\n- **Automagic Promotion of Scalar to List for Virtual Methods**\n- **Defining Custom Virtual Methods**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Template::Manual::VMethods",
        "section": "",
        "mode": "perldoc",
        "summary": "Template::Manual::VMethods - Virtual Methods",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "Scalar Virtual Methods",
                "lines": 210,
                "subsections": []
            },
            {
                "name": "Hash Virtual Methods",
                "lines": 140,
                "subsections": []
            },
            {
                "name": "List Virtual Methods",
                "lines": 181,
                "subsections": []
            },
            {
                "name": "Automagic Promotion of Scalar to List for Virtual Methods",
                "lines": 37,
                "subsections": []
            },
            {
                "name": "Defining Custom Virtual Methods",
                "lines": 23,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Template::Manual::VMethods - Virtual Methods\n",
                "subsections": []
            },
            "Scalar Virtual Methods": {
                "content": "chunk(size)\nSplits the value into a list of chunks of a certain size.\n\n[% ccardno = \"1234567824683579\";\nccardno.chunk(4).join\n%]\n\nOutput:\n\n1234 5678 2468 3579\n\nIf the size is specified as a negative number then the text will be chunked from right-to-left.\nThis gives the correct grouping for numbers, for example.\n\n[% number = 1234567;\nnumber.chunk(-3).join(',')\n%]\n\nOutput:\n\n1,234,567\n\ncollapse\nReturns the text with any leading and trailing whitespace removed and any internal sequences of\nwhitespace converted to a single space\n\n[% text = \"  The bird\\n  is the word\" %]\n[% text.collapse %]       # The bird is the word\n\ndefined\nReturns true if the value is defined.\n\n[% user = getuser(uid) IF uid.defined %]\n\ndquote\nReturns the text with any double quote characters escaped with a backslash prefix. Any newline\ncharacters in the text will be replaced with \"\\n\".\n\n[% quote = 'He said \"Oh really?\"' %]\n[% quote.dquote %]        # He said \\\"Oh really?\\\"\n\nhash\nReturn the value as a hash reference containing a single entry with the key \"value\" indicating\nthe original scalar value. As with the \"list\" virtual method, this is generally used to help\nmassage data into different formats.\n\nlcfirst\nReturns the text with the first letter converted to lower case.\n\n[% word = 'BIRD' %]\n[% word.lcfirst %]        # bIRD\n\nlength\nReturns the length of the string representation of the item:\n\n[% IF password.length < 8 %]\nPassword too short, dumbass!\n[% END %]\n\nempty\nReturns true if the string is empty:\n\n[% IF details.empty %]\nNo details specified\n[% END %]\n\nlist\nReturn the value as a single element list. This can be useful if you have a variable which may\ncontain a single item or a list and you want to treat them equally. The \"list\" method can be\ncalled against a list reference and will simply return the original reference, effectively a\nno-op.\n\n[% thing.list.size %]     # thing can be a scalar or a list\n\nlower\nReturns the text in lower case.\n\n[% word = 'BIRD' %]\n[% word.lower %]          # bird\n\nmatch(pattern, global)\nPerforms a regular expression match on the string using the pattern passed as an argument. If\nthe pattern matches the string then the method returns a reference to a list of any strings\ncaptured within parenthesis in the pattern.\n\n[% name = 'Larry Wall' %]\n[% matches = name.match('(\\w+) (\\w+)') %]\n[% matches.1 %], [% matches.0 %]    # Wall, Larry\n\nIf the pattern does not match then the method returns false, rather than returning an empty list\nwhich Perl and the Template Toolkit both consider to be a true value. This allows you to write\nexpression like this.\n\n[% \"We're not worthy!\" IF name.match('Larry Wall') %]\n\n[% IF (matches = name.match('(\\w+) (\\w+)')) %]\npattern matches: [% matches.join(', ') %]\n[% ELSE %]\npattern does not match\n[% END %]\n\nAny regex modifiers, like \"/s\", should be added in the regex using the \"(?s)\" syntax. For\nexample, to modify the regex to disregard whitespace (the \"/x\" switch), use:\n\n[% re = '(?x)\n(\\w+)\n[ ]\n(\\w+)\n';\nmatches = name.match(re);\n%]\n\nTo perform a global search to match the pattern as many times as it appears in the source\nstring, provide a true value for the \"global\" argument following the pattern.\n\n[% text = 'bandanna';\ntext.match('an+', 1).join(', )      # an, ann\n%]\n\nrepeat(n)\nRepeat the string a specified number of times.\n\n[% name = 'foo' %]\n[% name.repeat(3) %]                # foofoofoo\n\nreplace(search, replace)\nOutputs the string with all instances of the first argument (specified as a Perl regular\nexpression) with the second.\n\n[% name = 'foo, bar & baz' %]\n[% name.replace('\\W+', '') %]        # foobarbaz\n\nYou can use $1, $2, etc., to reference captured parts (in parentheses) in the regular\nexpression. Just be careful to *single* quote the replacement string. If you use *double* quotes\nthen TT will try and interpolate the variables before passing the string to the \"replace\"\nvmethod.\n\n[% name = 'FooBarBaz' %]\n[% name.replace('([A-Z])', ' $1') %]  # Foo Bar Baz\n\nremove(pattern)\nOutputs the string with all instances of the pattern (specified as a Perl regular expression)\nremoved.\n\n[% name = 'foo, bar & baz' %]\n[% name.remove('\\W+') %]    # foobarbaz\n\nsearch(pattern)\nPerforms a similar function to match but simply returns true if the string matches the regular\nexpression pattern passed as an argument.\n\n[% name = 'foo bar baz' %]\n[% name.search('bar') ? 'bar' : 'no bar' %]     # bar\n\nThis virtual method is now deprecated in favour of match. Move along now, there's nothing more\nto see here.\n\nsize\nAlways returns 1 for scalar values. This method is provided for consistency with the hash and\nlist size methods.\n\nsplit(pattern)\nCalls Perl's \"split()\" function to split a string into a list of strings.\n\n[% FOREACH dir IN mypath.split(':') %]\n[% dir %]\n[% END %]\n\nsubstr(offset, length, replacement)\nReturns a substring starting at \"offset\", for \"length\" characters.\n\n[% str 'foo bar baz wiz waz woz') %]\n[% str.substr(4, 3) %]    # bar\n\nIf \"length\" is not specified then it returns everything from the \"offset\" to the end of the\nstring.\n\n[% str.substr(12) %]      # wiz waz woz\n\nIf both \"length\" and \"replacement\" are specified, then the method replaces everything from\n\"offset\" for \"length\" characters with $replacement. The substring removed from the string is\nthen returned.\n\n[% str.substr(0, 11, 'FOO') %]   # foo bar baz\n[% str %]                        # FOO wiz waz woz\n\nsquote\nReturns the text with any single quote characters escaped with a backslash prefix.\n\n[% tim = \"Tim O'Reilly\" %]\n[% tim.squote %]          # Tim O\\'Reilly\n\ntrim\nReturns the text with any leading and trailing whitespace removed.\n\n[% text = '  hello  world  ' %]\n[% text.trim %]           # hello  world\n\nucfirst\nReturns the text with the first letter converted to upper case.\n\n[% word = 'bird' %]\n[% word.ucfirst %]        # Bird\n\nupper\nReturns the text in upper case.\n\n[% word = 'bird' %]\n[% word.upper %]          # BIRD\n",
                "subsections": []
            },
            "Hash Virtual Methods": {
                "content": "keys\nReturns a list of keys in the hash. They are not returned in any particular order, but the order\nis the same as for the corresponding values method.\n\n[% FOREACH key IN hash.keys %]\n* [% key %]\n[% END %]\n\nIf you want the keys in sorted order, use the list \"sort\" method.\n\n[% FOREACH key IN hash.keys.sort %]\n* [% key %]\n[% END %]\n\nHaving got the keys in sorted order, you can then use variable interpolation to fetch the value.\nThis is shown in the following example by the use of $key to fetch the item from \"hash\" whose\nkey is stored in the \"key\" variable.\n\n[% FOREACH key IN hash.keys.sort %]\n* [% key %] = [% hash.$key %]\n[% END %]\n\nAlternately, you can use the \"pairs\" method to get a list of key/value pairs in sorted order.\n\nvalues\nReturns a list of the values in the hash. As with the \"keys\" method, they are not returned in\nany particular order, although it is the same order that the keys are returned in.\n\n[% hash.values.join(', ') %]\n\nitems\nReturns a list of both the keys and the values expanded into a single list.\n\n[% hash = {\na = 10\nb = 20\n};\n\nhash.items.join(', ')    # a, 10, b, 20\n%]\n\neach\nThis method currently returns the same thing as the \"items\" method.\n\nHowever, please note that this method will change in the next major version of the Template\nToolkit (v3) to return the same thing as the \"pairs\" method. This will be done in an effort to\nmake these virtual method more consistent with each other and how Perl works.\n\nIn anticipation of this, we recommend that you stop using \"hash.each\" and instead use\n\"hash.items\".\n\npairs\nThis method returns a list of key/value pairs. They are returned in sorted order according to\nthe keys.\n\n[% FOREACH pair IN product.pairs %]\n* [% pair.key %] is [% pair.value %]\n[% END %]\n\nlist\nReturns the contents of the hash in list form. An argument can be passed to indicate the desired\nitems required in the list: \"keys\" to return a list of the keys (same as \"hash.keys\"), \"values\"\nto return a list of the values (same as \"hash.values\"), \"each\" to return as list of key and\nvalues (same as \"hash.each\"), or \"pairs\" to return a list of key/value pairs (same as\n\"hash.pairs\").\n\n[% keys   = hash.list('keys') %]\n[% values = hash.list('values') %]\n[% items  = hash.list('each') %]\n[% pairs  = hash.list('pairs') %]\n\nWhen called without an argument it currently returns the same thing as the \"pairs\" method.\nHowever, please note that this method will change in the next major version of the Template\nToolkit (v3) to return a reference to a list containing the single hash reference (as per the\nscalar list method).\n\nIn anticipation of this, we recommend that you stop using \"hash.list\" and instead use\n\"hash.pairs\".\n\nsort, nsort\nReturn a list of the keys, sorted alphabetically (\"sort\") or numerically (\"nsort\") according to\nthe corresponding values in the hash.\n\n[% FOREACH n IN phones.sort %]\n[% phones.$n %] is [% n %],\n[% END %]\n\nimport\nThe \"import\" method can be called on a hash array to import the contents of another hash array.\n\n[% hash1 = {\nfoo = 'Foo'\nbar = 'Bar'\n}\nhash2 = {\nwiz = 'Wiz'\nwoz = 'Woz'\n}\n%]\n\n[% hash1.import(hash2) %]\n[% hash1.wiz %]             # Wiz\n\nYou can also call the \"import()\" method by itself to import a hash array into the current\nnamespace hash.\n\n[% user = { id => 'lwall', name => 'Larry Wall' } %]\n[% import(user) %]\n[% id %]: [% name %]        # lwall: Larry Wall\n\ndefined, exists\nReturns a true or false value if an item in the hash denoted by the key passed as an argument is\ndefined or exists, respectively.\n\n[% hash.defined('somekey') ? 'yes' : 'no' %]\n[% hash.exists('somekey') ? 'yes' : 'no' %]\n\nWhen called without any argument, \"hash.defined\" returns true if the hash itself is defined\n(e.g. the same effect as \"scalar.defined\").\n\ndelete\nDelete one or more items from the hash.\n\n[% hash.delete('foo', 'bar') %]\n\nsize\nReturns the number of key/value pairs in the hash.\n\nempty\nReturns true if the hash is empty:\n\n[% IF config.empty %]\nNo configuration available\n[% END %]\n\nitem\nReturns an item from the hash using a key passed as an argument.\n\n[% hash.item('foo') %]  # same as hash.foo\n",
                "subsections": []
            },
            "List Virtual Methods": {
                "content": "first, last\nReturns the first/last item in the list. The item is not removed from the list.\n\n[% results.first %] to [% results.last %]\n\nIf either is given a numeric argument \"n\", they return the first or last \"n\" elements:\n\nThe first 5 results are [% results.first(5).join(\", \") %].\n\nsize, max\nReturns the size of a list (number of elements) and the maximum index number (size - 1),\nrespectively.\n\n[% results.size %] search results matched your query\n\nempty\nReturns true if the list is empty:\n\n[% IF results.empty %]\nNo results found\n[% END %]\n\ndefined\nReturns a true or false value if the item in the list denoted by the argument is defined.\n\n[% list.defined(3) ? 'yes' : 'no' %]\n\nWhen called without any argument, \"list.defined\" returns true if the list itself is defined\n(e.g. the same effect as \"scalar.defined\").\n\nreverse\nReturns the items of the list in reverse order.\n\n[% FOREACH s IN scores.reverse %]\n...\n[% END %]\n\njoin\nJoins the items in the list into a single string, using Perl's \"join()\" function.\n\n[% items.join(', ') %]\n\ngrep\nReturns a list of the items in the list that match a regular expression pattern.\n\n[% FOREACH directory.files.grep('\\.txt$') %]\n...\n[% END %]\n\nsort, nsort\nReturns the items in alpha (\"sort\") or numerical (\"nsort\") order.\n\n[% library = books.sort %]\n\nAn argument can be provided to specify a search key. Where an item in the list is a hash\nreference, the search key will be used to retrieve a value from the hash which will then be used\nas the comparison value. Where an item is an object which implements a method of that name, the\nmethod will be called to return a comparison value.\n\n[% library = books.sort('author') %]\n\nIn the example, the \"books\" list can contains hash references with an \"author\" key or objects\nwith an \"author\" method.\n\nYou can also specify multiple sort keys.\n\n[% library = books.sort('author', 'title') %]\n\nIn this case the books will be sorted primarily by author. If two or more books have authors\nwith the same name then they will be sorted by title.\n\nunshift(item), push(item)\nThe \"push()\" method adds an item or items to the end of list.\n\n[% mylist.push(foo) %]\n[% mylist.push(foo, bar) %]\n\nThe \"unshift()\" method adds an item or items to the start of a list.\n\n[% mylist.unshift(foo) %]\n[% mylist.push(foo, bar)    %]\n\nshift, pop\nRemoves the first/last item from the list and returns it.\n\n[% first = mylist.shift %]\n[% last  = mylist.pop   %]\n\nunique\nReturns a list of the unique elements in a list, in the same order as in the list itself.\n\n[% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]\n[% numbers = mylist.unique %]\n\nWhile this can be explicitly sorted, it is not required that the list be sorted before the\nunique elements are pulled out (unlike the Unix command line utility).\n\n[% numbers = mylist.unique.sort %]\n\nimport\nAppends the contents of one or more other lists to the end of the current list.\n\n[% one   = [ 1 2 3 ];\ntwo   = [ 4 5 6 ];\nthree = [ 7 8 9 ];\none.import(two, three);\none.join(', );     # 1, 2, 3, 4, 5, 6, 7, 8, 9\n%]\n\nmerge\nReturns a list composed of zero or more other lists:\n\n[% listone = [ 1 2 3 ];\nlisttwo = [ 4 5 6 ];\nlistthree = [ 7 8 9 ];\nlistfour = listone.merge(listtwo, listthree);\n%]\n\nThe original lists are not modified.\n\nslice(from, to)\nReturns a slice of items in the list between the bounds passed as arguments. If the second\nargument, \"to\", isn't specified, then it defaults to the last item in the list. The original\nlist is not modified.\n\n[% firstthree = list.slice(0,2) %]\n[% lastthree  = list.slice(-3, -1) %]\n\nsplice(offset, length, list)\nBehaves just like Perl's \"splice()\" function allowing you to selectively remove and/or replace\nelements in a list. It removes \"length\" items from the list, starting at \"offset\" and replaces\nthem with the items in \"list\".\n\n[% playgame = [ 'play', 'scrabble' ];\npingpong = [ 'ping', 'pong' ];\nredundant = playgame.splice(1, 1, pingpong);\nredundant.join;     # scrabble\nplaygame.join;     # play ping pong\n%]\n\nThe method returns a list of the items removed by the splice. You can use the \"CALL\" directive\nto ignore the output if you're not planning to do anything with it.\n\n[% CALL playgame.splice(1, 1, pingpong) %]\n\nAs well as providing a reference to a list of replacement values, you can pass in a list of\nitems.\n\n[% CALL list.splice(-1, 0, 'foo', 'bar') %]\n\nBe careful about passing just one item in as a replacement value. If it is a reference to a list\nthen the contents of the list will be used. If it's not a list, then it will be treated as a\nsingle value. You can use square brackets around a single item if you need to be explicit:\n\n[% # push a single item, anitem\nCALL list.splice(-1, 0, anitem);\n\n# push the items from anotherlist\nCALL list.splice(-1, 0, anotherlist);\n\n# push a reference to anotherlist\nCALL list.splice(-1, 0, [ anotherlist ]);\n%]\n\nhash\nReturns a reference to a hash array comprised of the elements in the list. The even-numbered\nelements (0, 2, 4, etc) become the keys and the odd-numbered elements (1, 3, 5, etc) the values.\n\n[% list = ['pi', 3.14, 'e', 2.718] %]\n[% hash = list.hash %]\n[% hash.pi %]               # 3.14\n[% hash.e  %]               # 2.718\n\nIf a numerical argument is provided then the hash returned will have keys generated for each\nitem starting at the number specified.\n\n[% list = ['beer', 'peanuts'] %]\n[% hash = list.hash(1) %]\n[% hash.1  %]               # beer\n[% hash.2  %]               # peanuts\n",
                "subsections": []
            },
            "Automagic Promotion of Scalar to List for Virtual Methods": {
                "content": "In addition to the scalar virtual methods listed in the previous section, you can also call any\nlist virtual method against a scalar. The item will be automagically promoted to a single\nelement list and the appropriate list virtual method will be called.\n\nOne particular benefit of this comes when calling subroutines or object methods that return a\nlist of items, rather than the preferred reference to a list of items. In this case, the\nTemplate Toolkit automatically folds the items returned into a list.\n\nThe upshot is that you can continue to use existing Perl modules or code that returns lists of\nitems, without having to refactor it just to keep the Template Toolkit happy (by returning\nreferences to list). \"Class::DBI\" module is just one example of a particularly useful module\nwhich returns values this way.\n\nIf only a single item is returned from a subroutine then the Template Toolkit assumes it meant\nto return a single item (rather than a list of 1 item) and leaves it well alone, returning the\nsingle value as it is. If you're executing a database query, for example, you might get 1 item\nreturned, or perhaps many items which are then folded into a list.\n\nThe \"FOREACH\" directive will happily accept either a list or a single item which it will treat\nas a list. So it's safe to write directives like this, where we assume that the \"something\"\nvariable is bound to a subroutine which may return one or more items:\n\n[% FOREACH item IN something %]\n...\n[% END %]\n\nThe automagic promotion of scalars to single item lists means that you can also use list virtual\nmethods safely, even if you only get one item returned. For example:\n\n[% something.first   %]\n[% something.join    %]\n[% something.reverse.join(', ') %]\n\nNote that this is very much a last-ditch behaviour. If the single item return is an object with\na \"first\" method, for example, then that will be called, as expected, in preference to the list\nvirtual method.\n",
                "subsections": []
            },
            "Defining Custom Virtual Methods": {
                "content": "You can define your own virtual methods for scalars, lists and hash arrays. The Template::Stash\npackage variables $SCALAROPS, $LISTOPS and $HASHOPS are references to hash arrays that define\nthese virtual methods. \"HASHOPS\" and \"LISTOPS\" methods are subroutines that accept a hash/list\nreference as the first item. \"SCALAROPS\" are subroutines that accept a scalar value as the\nfirst item. Any other arguments specified when the method is called will be passed to the\nsubroutine.\n\n# load Template::Stash to make method tables visible\nuse Template::Stash;\n\n# define list method to return new list of odd numbers only\n$Template::Stash::LISTOPS->{ odd } = sub {\nmy $list = shift;\nreturn [ grep { $ % 2 } @$list ];\n};\n\nExample template:\n\n[% primes = [ 2, 3, 5, 7, 9 ] %]\n[% primes.odd.join(', ') %]         # 3, 5, 7, 9\n\nTODO: document the definevmethod() method which makes this even easier\n",
                "subsections": []
            }
        }
    }
}