Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

$pu->users returns an array of all the users. When you assign that return value to a scalar with

my $users = $pu->users;

you put the array in scalar context, which returns the size of the array.

Instead, assign the results to an array, and put a reference to that array in the stash:

my @users = $pu->users;
$self->stash( users => \@users );

Alternatively, you can use an anonymous array reference like this:

$self->stash( users => [ $pu->users ] );

In your template, you'll have to dereference the array to loop over it:

__DATA__

@@ test.html.ep
<ul>
  <% foreach my $user (@$users) { %>
  <li><%= $user %></li>
  <% } %>
</ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top