1
votes

To give some context my controller selects an array ref from a query. Then the results get printed in the template like this.

home.html.ep

 <td> <%= @$query_result[0]->{data} %> </td>    
 <td> <%= @$query_result[1]->{data} %> </td>  
 ....  
 <td> <%= @$query_result[27]->{data} %> </td>    

Due to some results not existing, Mojolicious throws an error ( can't use undef hash value ... )
What I am trying to do:
When Mojolicious gets to the undef hash key/value to print 'No Data'.
I have tried like this :

  <td> <%= @$query_result[27]->{data} || 'no data' %> </td>   
  or    
  <td> % (exists(@$query_result[27]->{data})) ? <%= @$query_result[27]->{data} %> : 'no data' </td>   
  or 
  <td>
  % if (exists($query_result[27]->{data})) {
  <%= $query_result[27]->{data} %>
  % } else { 
  'No data'
  % }

I can't just remove <%= $query_result[27]->{data} %> because its returned from a query that runs on different parameters and only some parameters dont return the 27th array.

Is there a way to achieve what im trying? Thank you!

1
Try this: <td> <%= exists $query_result[27]->{data} ? @{$query_result[27]->{data}} : 'no data' %> </td> - Håkon Hægland
This seems not to work: Global symbol "@query_result" requires explicit package name (did you forget to declare "my @query_result"?) at template Did you mean this? <td><%= $query_result->[27] ? @$query_result[27]->{data} : 'no data' </td> - rooger
Just as a note, @$query_result[27]->{data} is a little bit of nonsense; it's saying to dereference $query_result and take a list slice, of a list with just the element 27. What you meant was $$query_result[27]->{data} which would be more commonly written as $query_result->[27]{data} (arrows between brackets are optional). Remember that the type of brackets determine the data structure you're dereferencing as, the sigil determines whether you're retrieving a single element or a list. - Grinnz

1 Answers

3
votes

It looks like you are trying to show all the indexes from 0 to 27, or less. You probably want to use a loop for that.

% foreach my $i ( 0 .. scalar @$query_result ) {
<td> <%= @$query_result[$i]->{data} %> </td>    
% }

Now you don't have to care about the number of columns any more. Do the same for the headings and you're golden.


Alternatively, you need to check if there is something in $query_result->[27] before you can do an exists check, because an undef (i.e. no value) cannot be used like a hash reference.

<td><%= $query_result->[27] ? @$query_result[27]->{data} : 'no data' </td>