PERL tk module handling - perl

I am using tk module to build a checklist for user to choose. I am totally beginner to this module. Currently the checklist created is all in the same series column, since it will be a long list, any idea how could I separate few of the options to another column? Also, any idea how to align those text to the left while checkbox to the right? To display it cleanly and neatly.
#!/usr/bin/perl
use Tk;
$main = MainWindow->new();
$label = $main->Label(-text => "Presence Check");
$label->pack();
$frame = $main->Frame(-relief=>"groove", -borderwidth=>2);
#$frame = $main->Frame(-relief=>"groove", -borderwidth=>2)->pack(-side => 'top', -expand => 1, -fill =>'both');
#$frame = $main->Frame->pack(-side => 'left', -fill => 'x');
$check1 = $frame->Checkbutton(-text=>"Document A (docx, pdf)",
-variable=>\$a,
-onvalue=>"APRESENT",
-offvalue=>"AABSENT");
#$check1->pack(-side=>"top");
$check2 = $frame->Checkbutton(-text=>"Document B (xlsx)",
-variable=>\$b,
-onvalue=>"BPRESENT",
-offvalue=>"BABSENT");
$check2->pack(-side=>"top");
$check3 = $frame->Checkbutton(-text=>"C specification",
-variable=>\$c,
-onvalue=>"CPRESENT",
-offvalue=>"CABSENT");
$check3->pack(-side=>"top");
$check4 = $frame->Checkbutton(-text=>"A-Specification",
-variable=>\$aspec,
-onvalue=>"ASPECPRESENT",
-offvalue=>"ASPECSABSENT");
$check4->pack(-side=>"top");
$check5 = $frame->Checkbutton(-text=>"Important Report",
-variable=>\$report,
-onvalue=>"REPORTPRESENT",
-offvalue=>"REPORTSABSENT");
$check5->pack(-side=>"top");
$check6 = $frame->Checkbutton(-text=>"Handbook",
-variable=>\$handbook,
-onvalue=>"HANDBOOKPRESENT",
-offvalue=>"HANDBOOKABSENT");
$check6->pack(-side=>"top");
$check7 = $frame->Checkbutton(-text=>"Data Spreadsheet",
-variable=>\$dataxls,
-onvalue=>"DATAPRESENT",
-offvalue=>"DATAABSENT");
$check7->pack(-side=>"top");
$check8 = $frame->Checkbutton(-text=>"D file",
-variable=>\$dfile,
-onvalue=>"DFILEPRESENT",
-offvalue=>"DFILEABSENT");
$check8->pack(-side=>"top");
$check10 = $frame->Checkbutton(-text=>"xx doc",
-variable=>\$xxdoc,
-onvalue=>"XXDOCPRESENT",
-offvalue=>"XXDOCABSENT");
$check10->pack(-side=>"top");
$check18 = $frame->Checkbutton(-text=>"yy Doc",
-variable=>\$yydoc,
-onvalue=>"YYDOCPRESENT",
-offvalue=>"YYDOCABSENT");
$check18->pack(-side=>"top");
$frame->pack();
$button = $main->Button(-text => "Exit",
-command => \&exit_button);
$button->pack();
MainLoop();
sub exit_button {
print "$a $b $c $aspec $report $handbook $dataxls $dfile $xxdoc $yydoc \n";
#print "$rv\n";
exit,
}

... any idea how could I separate few of the options to another
column? Also, any idea how to align those text to the left while
checkbox to the right?
Here is an example of how you can use the grid geometry manager to align the labels and checkboxes:
use feature qw(say);
use strict;
use warnings;
use Tk;
my $mw = MainWindow->new();
my #label_texts = (
"Document A (docx, pdf)",
"Document B (xlsx)",
"C specification"
);
my #labels;
my #checkvars;
my #check_buttons;
for my $text ( #label_texts ) {
my $label = $mw->Label(-text => $text);
push #labels, \$label;
my $check_var;
my $check = $mw->Checkbutton(
-text=>"",
-variable=>\$check_var,
);
push #checkvars, \$check_var;
push #check_buttons, \$check;
Tk::grid($label, $check, -sticky => 'w');
}
my $button = $mw->Button(
-text => "Exit",
-command => \&exit_button
);
Tk::grid($button, "-");
MainLoop();
sub exit_button {
for my $i (0..$#checkvars) {
my $var = $checkvars[$i];
my $state = $$var;
$state = 'undef' if !defined $state;
say "Variable $i: ", $state;
}
exit;
}

Please see attached screenshot to this code snippet if it is what you desired
!/usr/bin/perl
#
# vim: ai:ts=4:sw=4
#
use strict;
use warnings;
use feature 'say';
use Tk;
use Data::Dumper;
my $main = MainWindow->new( -title => 'Checkboxes' );
my $label = $main->Label(-text => 'Presence Check');
$label->pack();
my $frame = $main->Frame(-relief=>'groove', -borderwidth=>2);
my $values;
my #chk_boxes = (
[\$values->{doc_a},'Document A (docx, pdf)'],
[\$values->{doc_b},'Document B (xlsx)'],
[\$values->{spec_c},'C specification'],
[\$values->{spec_a},'A-Specification'],
[\$values->{report},'Important Report'],
[\$values->{hand_b},'Handbook'],
[\$values->{data_s},'Data Spreadsheet'],
[\$values->{data_d},'D file'],
[\$values->{doc_xx},'xx doc'],
[\$values->{doc_yy},'yy Doc']
);
check_box(\#chk_boxes);
$frame->pack();
my $button = $main->Button(
-text => 'Exit',
-command => \&exit_button
);
$button->pack();
MainLoop();
sub exit_button {
while( my($k,$v) = each %{$values} ) {
say "$k => $v" if $v;
}
exit;
}
sub check_box {
my $data = shift;
my $index = 0;
for my $chk_box ( #{$data} ) {
my $column = $index % 2;
my $row = int($index/2);
$frame->Checkbutton(
-text => $chk_box->[1],
-variable => $chk_box->[0]
)->grid( -column => $column, -row => $row, -sticky => 'w');
$index++;
}
}
Perhaps following form of data input may be preferable
#!/usr/bin/perl
#
# vim: ai:ts=4:sw=4
#
use strict;
use warnings;
use feature 'say';
use Tk;
use Data::Dumper;
my $main = MainWindow->new( -title => 'Checkboxes' );
my $label = $main->Label(-text => 'Presence Check');
$label->pack();
my $frame = $main->Frame(-relief=>'groove', -borderwidth=>2);
my $values;
my #chk_boxes;
while( <DATA> ) {
chomp;
my($var,$desc) = split '\t';
push #chk_boxes, [\$values->{$var}, $desc];
}
check_box(\#chk_boxes);
$frame->pack();
my $button = $main->Button(
-text => 'Exit',
-command => \&exit_button
);
$button->pack();
MainLoop();
sub exit_button {
while( my($k,$v) = each %{$values} ) {
say "$k => $v" if $v;
}
exit;
}
sub check_box {
my $data = shift;
my $index = 0;
for my $chk_box ( #{$data} ) {
my $column = $index % 2;
my $row = int($index/2);
$frame->Checkbutton(
-text => $chk_box->[1],
-variable => $chk_box->[0]
)->grid( -column => $column, -row => $row, -sticky => 'w');
$index++;
}
}
__DATA__
doc_a Document A (docx, pdf)
doc_b Document B (xlsx)
spec_c C specification
spec_a A-Specification
report Important Report
hand_b Handbook
data_s Data Spreadsheet
data_d D file
doc_xx xx Doc
doc_yy yy Doc
Add-on:
sub check_box {
my $data = shift;
my $index = 0;
for my $chk_box ( #{$data} ) {
my $column = $index % 2;
my $row = int($index/2);
my $chk_x = $frame->Checkbutton(
-text => $chk_box->[1],
-variable => $chk_box->[0]
)->grid( -column => $column, -row => $row, -sticky => 'w');
$chk_x->select if $index == 4;
$index++;
}
}

Related

What is the purpose of passing undef to DBI's `do` method in this context?

I don't understand what undef is doing in this snippet:
$dbh->do (qq {
INSERT INTO todo SET t = NOW(), status = 'open', content = ?
}, undef, $content);
Can someone please explain? I think I understand the whole code, but not this where it came from.
use warnings;
use strict;
use lib q(/data/TEST/perl/lib);
use CGI qw(:standard);
use WebDB;
sub insert_item {
my $content = shift;
my $dbh;
$content =~ s/^\s+//;
$content =~ s/^\s+$//;
if ($content ne "") {
$dbh = WebDB::connect();
$dbh->do (qq {
INSERT INTO todo SET t = NOW(), status = 'open', content = ?
}, undef, $content);
$dbh->disconnect();
}
}
sub display_entry_form {
print start_form(-action=> url()),
"To-do item:", br (),
textarea ( -name => "content",
-value => "",
-override => 1,
-rows =>3,
-columns => 80),
br (),
submit(-name=> "choice", -value => "Submit"),
end_form();
}
print header(), start_html(-title=>"To-Do List", -bgcolor => "white"), h2("To-Do List");
my $choice = lc(param ("choice"));
if ($choice eq "") {
display_entry_form();
} elsif ( $choice eq "submit" ) {
insert_item(param("content"));
display_entry_form();
} else {
print p ("Logic error, unknown choice: $choice");
}
The do() method takes 3 arguments: the query, query attributes, and bind data. The undef in your example means that there are no attributes to apply.
See "do()" in DBI on CPAN.
$rows = $dbh->do($statement) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr, #bind_values) or die ...

How to create a value from file to desired format and assign to variable using perl?

Can someone please let me know how to achieve the below through Perl.
I have a CVS file with values like below.
i/p:
Symbol,A,B,C,D,E,F
66,.8500,.8500,1.1600,1.1600
O/P:
[['Symbol','A','B','C','D','E','F' ],
['66','.8500','.8500','1.1600','1.1600']];
and assign the same to a variable.
How can i able to achieve this through Perl script.
$sts = open( CSV, "< File.csv" );
while (<CSV>) {
$csv = $_;
chomp($csv);
#csv_rcd = split( ',', $csv );
foreach $cell (#csv_rcd) {
push #rowdata, $cell;
}
push #$somedata, #rowdata;
}
But the above code didn't produce the desired o/p.
use strict;
use Data::Dumper;
my $somedata;
while (my $csv = <DATA>) {
chomp $csv;
push #$somedata, [ split (',' , $csv)];
}
print Dumper($somedata);
__DATA__
Symbol,A,B,C,D,E,F
66,.8500,.8500,1.1600,1.1600
Here is a full example to use PDF::Table
use PDF::API2;
use PDF::Table;
my $somedata;
while (my $csv = <DATA>) {
chomp $csv;
push #$somedata, [ split (',' , $csv)];
}
my $pdftable = new PDF::Table;
my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
my $page = $pdf->page;
$pdftable->table($pdf, $page, $somedata, x => 50, w => 495, start_y => 500, start_h => 300,
padding => 5, background_color_odd => 'gray', background_color_even => 'lightblue');
$pdf->saveas();
__DATA__
Symbol,A,B,C,D,E,F
66,.8500,.8500,1.1600,1.1600

How to print the profile details individual lines

#!/usr/bin/perl -w
use WWW::LinkedIn;
use CGI; # load CGI routines
use CGI::Session;
$q = CGI->new; # create new CGI object
print $q->header, # create the HTTP header
$q->start_html('hello world'), # start the HTML
$q->h1('hello world'), # level 1 header
$q->end_html; # end the HTML
my $consumer_key = 'xxxxxxx';
my $consumer_secret = 'xxxxxxxxx';
my $li = WWW::LinkedIn->new(
consumer_key => $consumer_key,
consumer_secret => $consumer_secret,
);
if ( length( $ENV{'QUERY_STRING'} ) > 0 ) {
$buffer = $ENV{'QUERY_STRING'};
#pairs = split( /&/, $buffer );
foreach $pair (#pairs) {
( $name, $value ) = split( /=/, $pair );
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$in{$name} = $value;
}
$sid = $q->cookie('CGISESSID') || $q->param('CGISESSID') || undef;
$session = new CGI::Session( undef, $sid, { Directory => '/tmp' } );
my $access_token = $li->get_access_token(
verifier => $in{'oauth_verifier'},
request_token => $session->param("request_token"),
request_token_secret => $session->param("request_token_secret"),
);
undef($session);
my $profile_xml = $li->request(
request_url =>
'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,positions,industry,distance)',
access_token => $access_token->{token},
access_token_secret => $access_token->{secret},
);
print $profile_xml;
}
The output is printing in single line. I want to print that is separate line.
OUTPUT
aAVGFD34 jj DD 456456 2003 6 true ara systems Technology and Services Technology and Services 0
How can i get the each column value from the profile_xml variable?
id avsdff
first name jj
lastname dd
Simply use Data::Dumper and XML::Simple.
use Data::Dumper;
use XML::Simple; #you may want to install a specific package from your distribution
{...}
my $hash_ref = SimpeXML::XMLin($profile_xml);
print Dumper($hash_ref);
I do not know if you would like more beautifully output.
try just to make simple print out from your hash reference
foreach $key (keys %{$profile_xml}) {
print "$key $profile_xml->{$key}\n";
}
Here i am going the show the way to parse the data and print in the individual lines.
my $parser = XML::Parser->new( Style => 'Tree' );
my $tree = $parser->parse( $profile_xml );
#print Dumper( $tree ); you can use this see the data displayed in the tree formatted
my $UID = $tree->[1]->[4]->[2],"\n";
print "User ID:$UID";
print"</br>";
my $FirstName = $tree->[1]->[8]->[2],"\n";
print "First Name:$FirstName";
print"</br>";
For sample i have showed for UID and FirstName. And this is working fine.

How to print selected value with checkbutton in Tkx

I'm using the Tkx module to create a window populated with text values from a #list. Then I select one or more then one with a checkbutton. I want to print the already selected ones after pressing the 'OK' button but don't know how to pass the variables to the 'OK' -command => sub {}. Thanks.
use autodie;
use strict;
use warnings;
use Tkx;
my $mw = Tkx::widget->new( "." );
$mw->g_wm_title( "Listbox" );
$mw->m_configure( -background => "#191919" );
my $width = '700';
my $height = '500';
Tkx::update('idletasks');
$width ||= Tkx::winfo('reqwidth', $mw);
$height ||= Tkx::winfo('reqheight', $mw);
my $x = int((Tkx::winfo('screenwidth', $mw) / 2) - ($width / 2));
my $y = int((Tkx::winfo('screenheight', $mw) / 2) - ($height / 2));
$mw->g_wm_geometry($width . "x" . $height . "+" . $x . "+" . $y);
my #list = ('TEXT1', 'TEXT2', 'TEXT3', 'TEXT4', 'TEXT5');
for my $list (#list) {
my $cb = $mw->new_ttk__checkbutton(
-text => $list,
-onvalue => 1,
-offvalue => 0,
);
$cb->g_pack(
-anchor=>'w',
-side=>'top',
-fill => 'x'
);
}
my $ok = $mw->new_button(
-text => "OK",
-command => sub {
print "Selected Values";
Tkx::after(500, sub { $mw->g_destroy });
},
);
$ok->g_pack(
-anchor=>'c',
-side=>'bottom',
);
Tkx::MainLoop();
If you just want to find what checkboxes are selected:
my $settings;
for my $list (#list) {
my $cb = $mw->new_ttk__checkbutton(
-text => $list,
-onvalue => 1,
-offvalue => 0,
-variable => \$settings->{checkbuttons}->{$list},
);
$cb->g_pack(
-anchor=>'w',
-side=>'top',
-fill => 'x'
);
}
my $ok = $mw->new_button(
-text => "OK",
-command => sub {
print "Selected Values: [";
print join( ", ", grep { $settings->{checkbuttons}->{$_} } #list ), "]\n";
Tkx::after(500, sub { $mw->g_destroy });
},
);

Resize Notepad based on holding frame

I'm trying to get the notepad to expand when dragging the main
window .... and suggestions? I have it to where it reads the screen size but it won't keep the changing size of the window. All my attempts of add a loop have failed... is there anyway to create a loop or a constant call back?
#!/usr/bin/perl -w
use strict;
use Tkx;
use strict;
use LWP::Simple;
use LWP::UserAgent;
use Cwd;
use Tkx;
Tkx::package_require("Tktable");
Tkx::package_require("tile");
Tkx::package_require("style");
Tkx::style__use("as", -priority => 70);
Tkx::package_require('widget::scrolledwindow');
Tkx::package_require("BWidget");
our $VERSION = "1.00";
(my $progname = $0) =~ s,.*[\\/],,;
my $mw = Tkx::widget->new(".");
$mw->g_wm_title("Wikiget");
$mw->g_wm_minsize(500, 200);
cow();
Tkx::MainLoop();
exit;
sub cow
{
my $sw = $mw->new_ScrolledWindow();
my $sf = $sw->new_ScrollableFrame();
$sw->g_pack(-fill => "both", -expand => 1); $sw->setwidget($sf);
my $printer_frame = Tkx::widget->new($sf->getframe());
Tkx::update('idletasks');
my $x = int((Tkx::winfo('width', $mw))- 10);
my $y = int((Tkx::winfo('height', $mw)) - 50);
my $nb = $printer_frame->new_ttk__notebook(-height => $y, -width => $x);
$nb->g_pack(-fill => "both", -expand => 1);
my $fm1 = $nb->new_ttk__frame;
my $fm2 = $nb->new_ttk__frame;
$fm1->new_label(-text => 'Test1Test1Test1')->g_pack(qw/-anchor nw/);
$fm2->new_label(-text => 'Test2Test2Test2')->g_pack(qw/-anchor nw/);
$nb->add($fm1, -text => 'One');
$nb->add($fm2, -text => 'Two');
}