Search code examples
perlunixmojoliciouspasswdmojolicious-lite

Mojolicious and Passwd::Unix


I'm trying to return the list of Unix users on this perl script. I'm using the Mojolicious framework with Passwd::Unix.

References:

That's my code:

test.pl

#!/usr/bin/env perl
use Mojolicious::Lite;
use Passwd::Unix;

# Instance
my $pu = Passwd::Unix->new();

get '/' => sub {
  my $self = shift;
  my $users = $pu->users;

  $self->stash(
    users => $users
  );
} => 'test';

app->start;

__DATA__

@@ test.html.ep
<ul>
  <% foreach my $user ($users) { %>
  <li><%= $user %></li>
  <% } %>
</ul>

But instead of returning users, it prints only the total number of users.

Test file


Solution

  • Building on Jason Gray's comment, you might make a helper that provides the P::U instance, then call that from the template, like so:

    #!/usr/bin/env perl
    use Mojolicious::Lite;
    use Passwd::Unix;
    
    # Instance
    helper pu => sub { state $pu = Passwd::Unix->new };
    
    get '/' => 'test';
    
    app->start;
    
    __DATA__
    
    @@ test.html.ep
    <ul>
      % foreach my $user (pu->users) {
      <li><%= $user %></li>
      % }
    </ul>
    

    In fact for that matter, you could just make a helper that returns all the users:

    #!/usr/bin/env perl
    use Mojolicious::Lite;
    use Passwd::Unix;
    
    # Instance
    helper users => sub { Passwd::Unix->new->users };
    
    get '/' => 'test';
    
    app->start;
    
    __DATA__
    
    @@ test.html.ep
    <ul>
      % foreach my $user (users) {
      <li><%= $user %></li>
      % }
    </ul>
    

    Also: I debated using the TagHelpers form for the template, but decided against complicating the issue. That said, here is how you could do the template if you so chose:

    @@ test.html.ep
    
    %= tag ul => begin
      % foreach my $user (users) {
        %= tag li => $user
      % }
    % end
    

    But then again, I'm a big fan of the Mojo::Template and TagHelpers form personally, I know its not for everyone.