Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

tk option+value in variable?

by cniggeler (Sexton)
on Jan 25, 2019 at 20:24 UTC ( [id://1228990] : perlquestion . print w/replies, xml ) Need Help??

cniggeler has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'd like to use the -font option in a Tk Label if the font's been externally defined by the user. I'd also like to condense my lines of code by combining options I'm repeating. So I'd like something like this:
my $newfont = ''; # maybe font value read from user, results in # $newfont = "{liberation sans} 8 normal"; my $opt = "-fg => $fg, -bg => $bg"; $opt .= ", -font => $newfont" if length($newfont); $rw->Label(-text => "Col. 1", $opt, -padx => 10)->grid( $rw->Label(-text => "Col. 2", $opt, -padx => 11), $rw->Label(-text => "Col. 3", $opt, -padx => 11))
but I get this error message:
Tk::Error: Odd number of args to Tk::Label->new(...)
Nothing I could think of, including escaped quotes or eval(), has gotten around it, so for now I use an if-else that checks length($newfont) and repeats the Label widget creation, once with and once without -font.

Is this possible? I lack detailed perl knowledge, so probably something like \$${opt} would do the trick :-) Thanks!

Replies are listed 'Best First'.
Re: tk option+value in variable?
by choroba (Cardinal) on Jan 25, 2019 at 20:51 UTC
    No advanced referencing is needed, just use an array of options instead of a string:
    my @opt = (-fg => $fg, -bg => $bg); push @opt, -font => $newfont if length $newfont; $mw->Label(-text => "Col. 1", @opt, -padx => 10)->grid( $mw->Label(-text => "Col. 2", @opt, -padx => 11), $mw->Label(-text => "Col. 3", @opt, -padx => 11));
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Bingo! Thanks so much!

        Maybe this should be a nother top-level question, but can you tell me know you knew to promote my string to an array? I was playing with subroutines and arguments, and I found that all these generated the same answer (5):

        my $a = 2; my $b = 3; print &add($a, $b) . "\n"; my $opt = "$a, $b"; print &add(eval($opt)) . "\n"; my @opt = ($a, $b); print &add(@opt) . "\n"; exit; sub add { my ($x, $y) = @_; return ($x +$y); }
        Another area my knowledge is lacking is the dash notation for the options (-font => 'courier', for example); is that common in other areas of perl or specific to Tk?