【问题标题】:how to get username using perl template toolkit如何使用 perl 模板工具包获取用户名
【发布时间】:2011-12-26 04:28:03
【问题描述】:

我在从 windows 系统获取用户名时遇到问题。我尝试在 perl 中使用 getlogin 函数并打印出我的用户名,但我的问题是如何在模板工具包中访问此用户名。我试过这样

 #!/usr/bin/perl
 use warnings;
 use strict;
 use Data::Dumper; 
   use XML::Simple;
 use Template;
  my $username = getlogin || getpwuid($<) || "veeru";

   my $xml = new XML::Simple;
my $data = $xml->XMLin("data.xml", ForceArray=>['dat','employee','experience']);
  print $username;

 my $template = Template->new();
my $filename = 'output1.tex';
  $template->process(\*DATA, $data, $filename)
|| die "Template process failed: ", $template->error(), "\n";

system( "pdflatex $filename" );
  __DATA__
 \documentclass[a4paper,leqno,twoside]{article}
 \usepackage[latin1]{inputenc}
 \usepackage[english]{babel}
 \begin{document}

 Issued by {Name}
 \issuedby{ [% username %] }

 % Document title. Use \doctitleShort{} to insert a shorter title in the header.
 \doctitle{employee information of thie"scr"company}
 \doctitleShort{\@doctitle}

[% FOREACH comp IN company %]
[% comp.name %] 
[% comp.location%]
employeedata:
[% FOREACH employee IN comp.domain.java.employee %]

[% employee.name %][% employee.number %]

[% FOREACH obj IN data%]

[% FOREACH beha IN obj.employee %]

[% IF beha.number == employee.number && beha.name == employee.name %] 

 [% beha.address %],

  [% LAST %]
 [% END %]
   [% END %]
 [% END %]
 [% END %]
 [% END %]
  [% END %]
 \end{document}

但它没有在 pdf 中打印用户名,它在控制台上打印用户名,所以我在模板过程中访问用户名变量时犯了错误。请告诉我如何在模板中使用该用户名变量,如何在 pdf 中打印。

我的第二个问题是

\doctitle{employee information of thie"scr"company}

在上面一行文档标题是用模板过程编写的,我需要从 perl 代码中访问标题如何做到这一点。任何人都可以帮助我,因为这是我第一次使用模板过程。

【问题讨论】:

    标签: perl template-toolkit


    【解决方案1】:

    使用您传递给模板的 hashref(即$data),您需要包含您在模板中使用的任何变量。模板中的变量必须在 hashref 中有一个与您要使用的值对应的键。

    所以对于username

    $data->{username} = $username;
    $template->process(\*DATA, $data, $filename);
    

    同样,对于doctitle,您可以在您的 perl 代码中设置它(从而能够访问它):

    $data->{doctitle} = 'employee information of thie"scr"company';
    

    ...并在您的模板中使用它:

    \doctitle{[% doctitle %]}
    

    【讨论】:

      【解决方案2】:

      查看进程子程序here的API文档。如您所见,第二个参数是哈希引用。您所要做的就是将用户名、文档标题和 data.xml 添加到该哈希中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 2011-12-17
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-23
        相关资源
        最近更新 更多