Search code examples
perlhashcurses

Perl Curses::UI - Populate Buttonbox programmatically


I've been fiddling with this for awhile now and can't seem to come up with a solution on my own. I'm using Curses::UI to build a simple interface that will print out a list of strings belonging to a hash (keys), and when one is selected it will send the respective value off to another method.

EDIT: For clarities sake, I can hardcode a Buttonbox and it works without issue. But I don't know the labels of the buttons or the number I'll have ahead of time, so I need to be able to populate it programmatically.

The problem I'm currently facing is I don't know how to populate a Buttonbox widget programmatically. The documentation says the -buttons flag takes in an arrayref, but passing it an array results in a fatal error of

Invalid button definition.
It should be a HASH reference,
but is a ARRAY reference.

Passing it a hash reference works, but only populates the very last button definition. e.g.

%btnHash = (-label => 'Button 1', -value => 1, -label => 'Button 2', -value => 2);
$buttons = $win->add(
    'videoButtons', 'Buttonbox',
    -vertical   =>  1,
    -buttons    =>  [\%btnHash]
);

Results in only Button 2 being populated to the screen. I also tried sending in a hash with two buttons surrounded by the appropriate curly brackets for each, but that resulted in nothing being populated at all.

This is the relevant code snippet that I've been toying with

%btnHash = (-label => 'Button 1', -value => 1);
push(@btnArray,%btnHash);
%btnHash = (-label => 'Button 2', -value => 2);
push(@btnArray,%btnHash);

#Tried an Array of the literal button definitions, same fatal error as before.
#@btnArray = ({-label => 'Button 1', -value => 1},{-label => 'Button 2', -value => 2});

$buttons = $win->add(
    'videoButtons', 'Buttonbox',
    -vertical   =>  1,
    -buttons    =>  [\@btnArray]
);

It's not pretty but I've started throwing things against the wall to see what works. Even if I have to use a loop to constantly create a new hash and store that in an array that'd be fine, then again I might be massively overcomplicating this.


Solution

  • @btnArray = ({-label => 'Button 1', -value => 1},{-label => 'Button 2', -value => 2});
    $buttons = $win->add(
        'videoButtons', 'Buttonbox',
        -vertical   =>  1,
        -buttons    =>  \@btnArray
    );
    

    Works perfectly. Just had to get rid of the square brackets. D'oh.