home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / perl-faq / ptk-faq / part3 < prev    next >
Encoding:
Internet Message Format  |  1997-06-01  |  38.3 KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!thetimes.pixel.kodak.com!news.kodak.com!news-pen-16.sprintlink.net!news-pen-4.sprintlink.net!news-east.sprintlink.net!news-dc-26.sprintlink.net!news-peer.sprintlink.net!news.sprintlink.net!Sprint!news.maxwell.syr.edu!news.cis.ohio-state.edu!nntp.sei.cmu.edu!bb3.andrew.cmu.edu!goldenapple.srv.cs.cmu.edu!rochester!cornellcs!newsstand.cit.cornell.edu!lnsnews.lns.cornell.edu!lns62.lns.cornell.edu!PVHP
  2. From: pvhp@lns62.lns.cornell.edu (Peter Prymmer)
  3. Newsgroups: comp.lang.perl.tk,comp.lang.perl.announce,comp.answers,news.answers
  4. Subject: comp.lang.perl.tk FAQ part3 of 5
  5. Followup-To: comp.lang.perl.tk
  6. Date: Sun, 01 Jun 1997 06:41:02 GMT
  7. Organization: Wilson Lab, Cornell U., Ithaca, NY, 14853
  8. Lines: 1107
  9. Approved: pvhp@lns62.lns.cornell.edu (Peter Prymmer)
  10. Expires: Thu, 31 Jul 1997 06:40:40 GMT
  11. Message-ID: <009B51BD.B5265A10@lns62.lns.cornell.edu>
  12. Reply-To: PVHP@lns62.lns.cornell.edu
  13. NNTP-Posting-Host: lns62.lns.cornell.edu
  14. Xref: senator-bedfellow.mit.edu comp.lang.perl.tk:4653 comp.lang.perl.announce:637 comp.answers:26265 news.answers:103806
  15.  
  16. Summary: comp.lang.perl.tk Frequently Asked Questions.
  17. Archive-name: perl-faq/ptk-faq/part3
  18. Posting-Frequency: monthly
  19. Last-modified: Date: Sat May 31 16:48:37 1997
  20. URL: http://w4.lns.cornell.edu/~pvhp/ptk/ptkFAQ.html
  21. Version: 1.00_07
  22.  
  23. URL (Hypertext-split): http://w4.lns.cornell.edu/~pvhp/ptk/ptkTOC.html
  24. URL (Plaintext): http://w4.lns.cornell.edu/~pvhp/ptk/ptkFAQ.txt
  25. Image-supplement: http://w4.lns.cornell.edu/~pvhp/ptk/ptkIMG.html
  26. ftp-Archive: ftp://ftp.ccd.bnl.gov/pub/ptk/ptkFAQ.txt
  27. ftp-Archive: ftp://rtfm.mit.edu/pub/usenet/perl-faq/ptk-faq/
  28. e-mail-Archive: ptkfaq@pubweb.bnl.gov
  29.  
  30. Perl/Tk FAQ part 3 of 5 - More Programming 
  31. ****************************************** 
  32.  
  33.  
  34.  
  35.  ______________________________________________________________________
  36.  
  37.  
  38.  
  39.  11. How do I get a Canvas to ... ? 
  40.  
  41.  The Canvas widget is the most configurable and versatile. With versatility
  42.  comes complication however, and it is certainly deserving of its own special
  43.  section within this FAQ... 
  44.  
  45.  You might also see the examples in the widget demo especially the "canvas
  46.  item types" selection (which runs the items.pl demo script). 
  47.  
  48.  ______________________________________________________________________
  49.  
  50.  
  51.  
  52.  11.1. Display a bitmap? 
  53.  
  54.  Unlike other widgets the Canvas does not take the -bitmap configuration
  55.  option. One of the ways to place things - including bitmaps - onto a Canvas
  56.  is to call create on it. To emphasize how a Canvas handles bitmaps
  57.  differently from the configurable widgets let me assume that you wanted to
  58.  specify the 'hourglass' built in bitmap in the following. (For more on xbm file
  59.  specification see a previous question [10.9] within this FAQ.) Here is a way to
  60.  combine the Canvas; and create; calls: 
  61.  
  62.      my($canvar) = $main->Canvas();
  63.      my($bittag) = $canvar->create('bitmap',10,10, -bitmap=>'hourglass');
  64.      $canvar->pack;
  65.  
  66.  You can also create an image that will display a bitmap (plus a whole lot
  67.  more): 
  68.  
  69.      my($canvar) = $main->Canvas();
  70.      my($bitmap) = $main->Bitmap(-data => $data);
  71.      my($bittag) = $canvar->create(qw(image 10 10), -image => $bitmap);
  72.      $canvar->pack;
  73.      MainLoop;
  74.  
  75.  ______________________________________________________________________
  76.  
  77.  
  78.  
  79.  11.2. Erase a display? 
  80.  
  81.  To erase something like a bitmap call delete on the item. Assuming your 
  82.  Canvas tag is $canvar and your item tag it $bittag (as in the previous
  83.  [11.1] question) then the call proceeds like: 
  84.  
  85.      $canvar -> delete($bittag);
  86.  
  87.  This is of course useful in a callback. For example to configure a Button to do
  88.  your deletion for you you could say something like: 
  89.  
  90.      $main->Button(-text   => 'clear', 
  91.                    -command=>sub{$canvar -> delete($bittag)}
  92.                   )->pack;
  93.  
  94.  To remove an entire MainWindow() call the withdraw() method: 
  95.  
  96.      $main -> withdraw;
  97.  
  98.  ______________________________________________________________________
  99.  
  100.  
  101.  
  102.  11.3. Display an Image? 
  103.  
  104.  Just as for the other widget types there is a two step process of first getting a "
  105.  Photo" handle on the file of interest. For the Canvas (unlike the other
  106.  widgets) one then makes a call to create an image as in the following
  107.  example where 'IMG' is the Photo handle for a GIF file that comes
  108.  distributed with the Tk kit (it just happens to be handled in this example via
  109.  the scalar variable $img): 
  110.  
  111.      #!/usr/bin/perl -w
  112.      use strict;
  113.      use Tk;
  114.      my $main = new MainWindow;
  115.      my $canvar = $main ->Canvas;
  116.      $canvar->pack;
  117.      my $file = 'demos/images/earth.gif';
  118.      my $img = 
  119.       $canvar->Photo( 'IMG', 
  120.                       -file => Tk->findINC($file) );
  121.  
  122.      $canvar->create( 'image',0,0, 
  123.                       '-anchor' => 'nw', 
  124.                       '-image'  => $img );
  125.  
  126.      MainLoop;
  127.      __END__
  128.  
  129.  ______________________________________________________________________
  130.  
  131.  
  132.  
  133.  11.4. What things can be created on a Canvas? 
  134.  
  135.  The following types can be used in $canvar->create calls: 
  136.  
  137.      arc        sections of circle
  138.      bitmap     for X11 bitmap files/builtins
  139.      image      for Photo image types (gif, xpm, xbm, ...) 
  140.      line
  141.      oval       includes circles
  142.      polygon    may be -filled
  143.      rectangle  may also be -filled
  144.      text       similar to Text widget primitive
  145.      window     allows embeddding of other widgets
  146.  
  147.  ______________________________________________________________________
  148.  
  149.  
  150.  
  151.  11.5. How do I redraw a line on a Canvas? 
  152.  
  153.  By calling the ->coord method on the item as in the following example: 
  154.  
  155.      #!/usr/bin/perl
  156.      use Tk;
  157.      $m = MainWindow->new;
  158.      $c = $m -> Canvas;
  159.      $i = $c -> create('line', 0,0 => 50,50 );
  160.      $c -> pack;
  161.      $b = $m -> Button('-text' => 'extend', 
  162.                        '-command' => sub{push_it($c,$i)},
  163.                       )->pack;
  164.      MainLoop;
  165.      
  166.      sub push_it {
  167.          my ($canvas, $line) = @_;
  168.          $canvas -> coords($line, 0,0 => 100,100 );
  169.      }
  170.  
  171.  Thanks to Christopher Dunn and Harry Bochner
  172.  <bochner@das.harvard.edu> for providing this question and answer. 
  173.  
  174.  ______________________________________________________________________
  175.  
  176.  
  177.  
  178.  11.6. How do I use the Canvas as a geometry manager? 
  179.  
  180.  In a call to create a window (or anything) on your Canvas you need to
  181.  specify its position - this is in part how a Canvas can be used as a geometry
  182.  manager. e.g.: 
  183.  
  184.      my($bittag) = $canvar->create('bitmap',10,10, -bitmap=>'hourglass');
  185.  
  186.  Specifies the x=10, y=10 screen pixel location (from the upper left). Other
  187.  possible units are: 
  188.  
  189.  
  190.      tag  unit             example
  191.           pixels           25,50   # i.e. no unit tag at all
  192.      m    milliimeters     10c,20c
  193.      c    centimeters      1c,2c
  194.      p    points (1/72")   35p,70p
  195.  
  196.  There can be a great deal more to it than just units, however. Note the
  197.  following question posed and answered by Eric J. Bohm. 
  198.  
  199.      Eric J. Bohm <bohm@cs.buffalo.edu> wrote:
  200.      !I've got a row of entries packed side by side in a frame.  
  201.      !These frames are packed on top of each other.  
  202.      !So, when someone deletes a row, the lower ones bubble 
  203.      !up automatically.  This works just fine and dandy, and let me
  204.      !extend my thanks to our brave and energetic pTk team.
  205.      !
  206.      !The trick here is what widget do I put this in so that 
  207.      !it will be scrollable when I have too many rows to 
  208.      !fit on the screen?
  209.        [details and complaints]
  210.  
  211.   Following up to my own message here. 
  212.  
  213.   All right, after several false leads, I spent 3 hours fighting a canvas
  214.   widget and pounding my head against the canvas.html doc, until I finally
  215.   understood how to include my entries in a frame in a window in the
  216.   canvas and get things to scroll nicely. 
  217.  
  218.   Turns out that the whole thing isn't all that hard to do once I understood
  219.   how canvas widgets work. 
  220.  
  221.   Not sure if its of general interest, but here's the snippet, which was stolen
  222.   from the items demo inside the widget_lib and then brutally hacked. 
  223.  
  224.   Perhaps a simpler demo would have been easier to use as a guide, but I
  225.   got there eventually, so my thanks for the widget demo.
  226.  
  227.      #----------------------------------------
  228.      my $c = $w_frame->Canvas();
  229.      $c->configure(
  230.           -height       => '300',
  231.           -width        => '600',
  232.           -relief       => 'sunken',
  233.           -bd => 2,
  234.       );
  235.       my $w_frame_vscroll = $w_frame->Scrollbar(
  236.                                           -command => ['yview', $c]
  237.                                                );
  238.       my $w_frame_hscroll = $w_frame->Scrollbar(
  239.                                           -orient => 'horiz', 
  240.                                           -command => ['xview', $c]
  241.                                                 );
  242.       $c->configure(-xscrollcommand => ['set', $w_frame_hscroll]);
  243.       $c->configure(-yscrollcommand => ['set', $w_frame_vscroll]);
  244.       $w_frame_hscroll->pack(-side => 'bottom', -fill => 'x');
  245.       $w_frame_vscroll->pack(-side => 'right', -fill => 'y');
  246.       $c->pack(-expand => 'yes', -fill => 'both',-side=>'top');
  247.       my $entryframe=$c->Frame;
  248.       my $c_win= create $c 'window','0','0',
  249.                            -window=>$entryframe,
  250.                            -anchor=>'nw';
  251.       #----------------------------------------
  252.  
  253.   Where $c -> configure( -scrollregion => [$top, $left,
  254.   $right, $bottom]) can be used to size things nicely once you find out
  255.   how big it'll be. 
  256.  
  257.   And the widgets you want scrolled should be slaves of $entryframe. 
  258.  
  259.   Vastly more robust than anything I had running in the BLT Table. 
  260.  
  261.   EJB 
  262.  
  263.  ______________________________________________________________________
  264.  
  265.  
  266.  
  267.  11.7. How do I get a Canvas to output PostScript(c)? 
  268.  
  269.  Many thanks to Tom Oelke <tpo9617@rit.edu> for providing this question,
  270.  answer & snippet of code: 
  271.  
  272.   The following section of code gets the postscript code for the section of
  273.   canvas that's top-left corner is at $min_x, $min_y, and has a width and
  274.   height equivalent to the displayed region. This ps code is then piped out
  275.   to lpr to be printed. 
  276.  
  277.      my $ps = $canvas->postscript( '-x' => $min_x,
  278.                                    '-y' => $min_y,
  279.                                    -width => $canv->Width,
  280.                                   -height => $canv->Height);
  281.      open (PS, "| lpr"); # customize with -Pname e.g. 
  282.      print PS $ps;
  283.      close (PS);
  284.  
  285.  Whereas you would use something like: 
  286.  
  287.      open (PS, ">file.ps"); # to output to a file
  288.      print PS $ps;
  289.      close (PS);
  290.  
  291.  ______________________________________________________________________
  292.  
  293.  
  294.  
  295.  11.8. How do I get a PostScript(c) output of a Canvas w/ widgets? 
  296.  
  297.  In general you don't. You can't do it in Tcl/Tk either (if that is any
  298.  consolation). Nick Ing-Simmons posted an explicit discussion of what is
  299.  involved: 
  300.  
  301.  
  302.  Subj: RE: Canvases and postscript output
  303.  
  304.  On Tue, 28 Nov 95 14:37:09 PST
  305.  Davis <morry@dsg.tandem.com> writes:
  306.  ! I have a canvas with text and some entry widgets that I want to create
  307.  !postscript from. I used the 
  308.  !widget->postscript( -file => 'ld.ps', -colormode  => 'gray');
  309.  !the file gets created but its empty. Is there some other options I need?
  310.  
  311.   Core Tk cannot write postscript for embedded windows, the best it could
  312.   do would be to grab a Pixmap of the window as displayed. This is fine if
  313.   the window is visible, but if it is scrolled off screen or under another
  314.   application there is no pixmap. 
  315.  
  316.   Only complete fix is to have a ->postscript method for every possible
  317.   widget which can render un-mapped widgets. This is non-trivial task. 
  318.  
  319.  
  320.  !Also I have a scrollbar for this canvas and when I scroll  the entry widget
  321.  !actually scroll part way out of the frame the canvas is in. Why does this
  322.  !happen and can I fix it? 
  323.  
  324.   The Entry widgets need to be descendants of the canvas or they just get
  325.   clipped to their parent. 
  326.  
  327.  ______________________________________________________________________
  328.  
  329.  
  330.  
  331.  11.9. How do I get the size of a Canvas? After a re-size? 
  332.  
  333.      $canvas->cget(-width);
  334.  
  335.  simply returns the size of the canvas when it was created, whereas 
  336.  
  337.      $canvas->Width;
  338.  
  339.  will get the answer even after a re-size. Substitute [Hh]eight for [Ww]idth
  340.  in the above if that is what you want. 
  341.  
  342.  Nick Ing-Simmons points out that if you want to have your Canvas be able to
  343.  grow to arbitrarily large sizes be sure to specify the -expand or -fill options
  344.  when you ->pack the Canvas. 
  345.  
  346.  ______________________________________________________________________
  347.  
  348.  
  349.  
  350.  11.10. How do I bind different actions to different areas of the same Canvas?
  351.  
  352.  KOBAYASI Hiroaki <kobayasi@sowa.is.uec.ac.jp> recently posted an
  353.  extraordinary little script that addresses this question quite succinctly: 
  354.  
  355.   How about this?
  356.   ## I don't know whether this is a good solution or not.
  357.   ## but it works under Tk-b9 + perl5.002b1f.
  358.  
  359.      
  360.      #!/usr/local/bin/perl -w
  361.      use Tk;
  362.      
  363.      ($c = MainWindow->new->Canvas)->
  364.         pack(-fill => 'both', -expand => 1);
  365.      # to survive under Tk-b8. 
  366.      # You don't need paren before pack in b9.
  367.      
  368.      ($pop1 = $c->Menu)->command(-label => "FOO");
  369.      ($pop2 = $c->Menu)->command(-label => "BAR");
  370.      
  371.      $c->create(oval => 0, 0, 100, 100, 
  372.                 -fill => 'black', 
  373.                 -tags => ['popup']);
  374.      
  375.      $c->Tk::bind($c, '<3>', [\&PopupOnlyThis, $pop1]);
  376.      $c->bind('popup', '<3>', [\&PopupOnlyThis, $pop2]);
  377.      
  378.      sub PopupOnlyThis {
  379.          print "@_\n";
  380.          my($c, $pop) = @_;
  381.      
  382.          # to prevent multiple popup.
  383.          Tk->break if defined $Tk::popup;
  384.      
  385.          my $e = $c->XEvent;
  386.          $pop->Popup($e->X, $e->Y);
  387.          # Tk::Menu::Popup sets $Tk::popup.
  388.      
  389.      }
  390.      MainLoop;
  391.      
  392.      $Tk::popup = undef; # to kill warning.
  393.      
  394.      __END__
  395.  
  396.  ______________________________________________________________________
  397.  
  398.  
  399.  
  400.  12. Common Problems. 
  401.  
  402.  Everything in Tk-land is a reference. When defining callbacks take care to
  403.  pass variables by reference. Callbacks are closures and to ensure a variable gets
  404.  its current value, as opposed to its value when the callback is defined, pass by
  405.  reference, e.g.: 
  406.  
  407.      $frog = 123;
  408.      $b = $mw->Button(
  409.          -text    => 'Push Me',
  410.          -command => [
  411.              sub {
  412.                 my($widget, $frog) = @ARG;
  413.                 print STDERR "widget=$widget!\n";
  414.                 print STDERR "frog=$$frog!\n";
  415.              }, $mw, \$frog,
  416.           ],
  417.      ); # end Button definition
  418.  
  419.  If $frog is not passed by reference the print statement will always output "
  420.  123" (actually, the print as it exists will print nothing since it's trying to
  421.  dereference $frog, which presumably is now not a reference). Note that by
  422.  definition all perl/Tk widgets are already references, since they're simply Perl
  423.  objects, and that's why you do not have to print $$widget! 
  424.  
  425.  A good "reference" for handling references and dereferencing are the 
  426.  perlref(1) and perlobj(1) man pages. A good "reference" for the
  427.  various data types you will encounter in this kind of perl programming is Tom
  428.  Christiansen's Perl Data Structures Cookbook which is now available as the 
  429.  perldsc(1) man page. 
  430.  
  431.  Also beware the traps that befall perl4 programmers in making the move to
  432.  perl 5. References for this include the new perltrap(1) man page as well as
  433.  William Middleton's perl425 trap document at: 
  434.  
  435.      http://www.perl.com/perl/all_about/perl425.html
  436.  or
  437.      http://w4.lns.cornell.edu/~pvhp/ptk/misc/perl425.html
  438.  
  439.  ______________________________________________________________________
  440.  
  441.  
  442.  
  443.  12.1. What do the ->, => and :: symbols mean? 
  444.  
  445.  The -> is the "infix dereference operator". In other words it is the means by
  446.  which one calls a sub with a pass by reference (among other things you can do
  447.  with ->). As stated above most things in calls to perl/Tk routines are passed
  448.  by reference. The -> is used in perl just as in C or C++. (Most of the widget
  449.  primitives are elements of the Tk:: "perl class".) A simple example of
  450.  dereferencing would be: 
  451.  
  452.      $x = { def => bar };  # $x is a reference to an anon. hash
  453.      print $x->{def},"\n"; # prints ``bar''
  454.  
  455.  Note that in the case of calling perl/Tk subs there may be more than one way
  456.  to call by reference. Compare 
  457.  
  458.      my($top) = MainWindow->new;
  459.  
  460.  with 
  461.  
  462.      my($top) = new MainWindow;
  463.  
  464.  But in general you will be making extensive use of calls like: 
  465.  
  466.      $top -> Widge-type;
  467.  
  468.  There is a clear and succint discussion of references, dereferences, and even
  469.  closures in man perlref(1) or see the perl 5 info page at: 
  470.  
  471.      http://www.metronet.com/perlinfo/perl5.html
  472.  
  473.  The use of the => operator is quite common in perl/Tk scripts. Quoting from 
  474.  man perlop(1): 
  475.  
  476.   The => digraph is simply a synonym for the comma operator. It's useful
  477.   for documenting arguments that come in pairs. 
  478.  
  479.  You could say that => is used for aesthetic or organizational reasons. Note in
  480.  the following how hard it is to keep track of whether or not every -option
  481.  has an argument: 
  482.  
  483.      $query -> Button(-in,\$reply,-side,'left',-padx,2m,-pady,
  484.       2m,-ipadx,2m,-ipady,1m)->pack(-side,'bottom');
  485.  
  486.  As opposed to: 
  487.  
  488.      $query ->Button( -in => \$reply,
  489.                       -side => 'left',
  490.                       -padx => 2m,
  491.                       -pady => 2m,
  492.                       -ipadx => 2m,
  493.                       -ipady => 1m
  494.                      )->pack(-side => 'bottom');
  495.  
  496.  By the way if you wanted the numeric "greater than or equal" you would use >=
  497.  not =>. 
  498.  
  499.  While the :: symbol can be thought of as similar to the period in a C struct, it
  500.  is much more akin to the :: class scope operator in C++: 
  501.  
  502.      a.b.c;       /* something in C */
  503.      a::b::c();   // function in C++ 
  504.      $a::b::c;    # a scalar in Perl 5
  505.      @a::b::c;    # a list in Perl 5
  506.      %a::b::c;    # an associative array or "hash" in Perl 5
  507.      &a::b::c;    # a function in Perl 5
  508.  
  509.  It is also analogous to the single forward quotation mark in perl 4: 
  510.  
  511.      $main'foo;   # a $foo scalar in perl 4
  512.      $main::foo;  # a $foo scalar in Perl 5
  513.  
  514.  For backward compatibility perl 5 allows you to refer to $main'foo but 
  515.  $main::foo is recommended. 
  516.  
  517.  ______________________________________________________________________
  518.  
  519.  
  520.  
  521.  12.2. What happened to the ampersands &? 
  522.  
  523.  Perl 4 programmers especially may be surprised to find that as of Perl 5.0 the
  524.  ampersand & may be omitted in a call to a subroutine if the subroutine has
  525.  been declared before being used. Actually you can even get around the declare
  526.  before omit ampersand rule by using the subs.pm pragma, or by
  527.  pre-declaring (without defining) as in a script like: 
  528.  
  529.      #!/usr/bin/perl -w
  530.      use strict;
  531.      use Tk;
  532.      sub Mysub;  #pre-declare allows calling Mysub()
  533.  
  534.      ...Other main/Tk stuff - 
  535.              including call to Mysub() sans &...
  536.  
  537.      sub Mysub {
  538.  
  539.          ...Mysub stuff...
  540.  
  541.      }
  542.  
  543.  Note however that one place the \& reference is sometimes used in perl/Tk in
  544.  the setting up a callback for a widget. Other references are possible: e.g. \$foo
  545.  is a reference to the scalar variable $foo (this was true even under perl 4). 
  546.  
  547.  ______________________________________________________________________
  548.  
  549.  
  550.  
  551.  12.3. What happened to the quotation marks? 
  552.  
  553.  Perl 4 programmers especially may be surprised to find a serious dearth of
  554.  quotation marks around strings in perl 5 scripts such as in perl/Tk. The "rules
  555.  have been relaxed" somewhat for the use of quotation marks. Basically it is
  556.  OK to leave them out if the context of the string in question is unambiguous.
  557.  However, it never hurts to leave them in and may help readability. 
  558.  
  559.  Here is Larry Wall's synopsis of the string situation: 
  560.  
  561.  Newsgroups: 
  562.     comp.lang.perl.misc 
  563.  Subject: 
  564.     Re: To string or not to string... 
  565.  
  566.  In article <4e49fv$j0u@panix3.panix.com>,
  567.  Andy Finkenstadt <genie@panix.com> wrote:
  568.  ! Back when I was learning perl (after receiving a review copy of
  569.  ! learning perl, and buying the real perl book, each from ORA),
  570.  ! I always got bit by when I needed to use "strings" and when
  571.  ! I could get away with bare_words within braces for associative
  572.  ! arrays.  (Yes, this is under 4.036 if it matters.)
  573.  ! 
  574.  ! the most typical example would be:
  575.  ! 
  576.  ! When must I use $assoc{"trailer"} and when can I get away with
  577.  ! $assoc{trailer}?   Similarly, $ENV{CONTENT_LENGTH} versus
  578.  ! $ENV{"CONTENT_LENGTH"}?  Unfortunately sometimes my strings
  579.  ! end up being numbers in their own right, i.e.:  $message{"0"}
  580.  ! or $msg=0; $message{$msg}.  Which is more appropriate,
  581.  ! which are merely stylistic, and which are stricly perl5
  582.  ! features now that I'm upgrading most of my installations
  583.  ! of perl.
  584.  
  585.   Perl 4 let you use a "bareword" for a string if it had no other
  586.   interpretation. It would warn you under -w if you used a word consisting
  587.   entirely of lower-case characters, since such a word might gain an
  588.   interpretation someday as a keyword. 
  589.  
  590.   Perl 5 still works the same way, but with several twists. 
  591.  
  592.   1. ) Since you can now call predeclared subroutines as though they were
  593.     builtins, you have to worry about collisions with subroutine names too.
  594.     However... 
  595.   2. ) You can completely disallow the default interpretation of barewords
  596.     by saying "use strict subs", which requires any such bareword to be a
  597.     predeclared subroutine. But... 
  598.   3. ) Overriding all that, Perl 5 (in recent versions) will FORCE string
  599.     interpretation of any bare identifier used where a single hash subscript
  600.     is expected, either within curlies or before a =>. (Those are the places
  601.     you might usually want the old barewords anyway.)
  602.  
  603.   The upshot of these rules is that you can write Perl 5 with much less
  604.   punctuation than Perl 4, yet also with less ambiguity. If you so choose. 
  605.  
  606.   Larry 
  607.  
  608.  Tcl programmers should note that in Perl the single quotation marks '' act
  609.  much as the curly brace {} enclosure does in Tcl (no escaping special
  610.  characters $@\ etc.). Whereas the double quotation marks "" allow for
  611.  substitution of $variables (the rules are a little different between Tcl and
  612.  Perl however). 
  613.  
  614.  Note also that a frequently seen short hand in perl5/Tk scripts is the @list
  615.  returned by qw(): 
  616.  
  617.      @list = qw(zoom schwartz bufigliano);
  618.  
  619.  which is equivalent to: 
  620.  
  621.      @list = split(' ','zoom schwartz bufigliano');
  622.  
  623.  or more simply: 
  624.  
  625.      @list = ('zoom','schwartz','bufigliano');
  626.  
  627.  i.e. the qw/STRING/ @list is not equivalent to the quotation marks provided
  628.  by q/STRING/, qq/STRING/, or qq(STRING)... 
  629.  
  630.  There are, ironically enough, situations in perl/Tk where one needs to use
  631.  quotation marks as in the following by post by <a904209@pluto.tiuk.ti.com>: 
  632.  
  633.  
  634.   Paul Wickman wrote in article <4b4o0fINNlu8@CS.UTK.EDU>:
  635.  !
  636.  !    Why does the following statement work fine:
  637.  !
  638.  !$day->pack(-before => $year, -side => 'left');
  639.  !
  640.  !    But the below generates the given error:
  641.  !
  642.  !$day->pack(-after => $year, -side => 'left');
  643.  !
  644.  !Ambiguous use of after => resolved to "after" => at line 191.
  645.  !
  646.  
  647.   Because there is a sub after in scope, probably imported from Tk via 
  648.   use Tk;. 
  649.  
  650.   There are two workrounds: 
  651.  
  652.      use Tk qw(MainLoop exit ...); # just ones you use
  653.  
  654.   or 
  655.  
  656.      $day->pack('-after' => $year, -side => 'left');
  657.  
  658.  ______________________________________________________________________
  659.  
  660.  
  661.  
  662.  12.4. Must I use "my" on all my variables? 
  663.  
  664.  If you use strict; (as recommended) the answer is "probably". This
  665.  confines the variables names to your namespace - so your variable does not
  666.  conflict with one in the module(s) your are using (you are at the least useing
  667.  Tk;). my does "lexical scoping" on a variable rather than the "dynamic
  668.  scoping" done by local (like auto variables in C). The difference between
  669.  these two is that the scope of my $var is confined to the block (sub, if, 
  670.  foreach, etc.) in which it is declared and used, as opposedto local $iable
  671.  which can propogate to all blocks called by the block in which it is declared. In
  672.  general the confined scope of my $var means that its use will proceed quicker
  673.  and more efficiently than local $iable. 
  674.  
  675.  If you give a fully qualified variable name such as 
  676.  
  677.      $main::var = 1;  # No "my" needed
  678.  
  679.  Then no my $var is needed. However, the lexical scoping of my $var makes
  680.  it preferable. 
  681.  
  682.  If you choose to use my (as recommended) then beware that you should
  683.  declare a variable my only at the first use (instantiation) of a variable.
  684.  Consider yet another way to re-write the "Hello World!" script: 
  685.  
  686.      #!/usr/local/bin/perl -w
  687.      use strict;
  688.      use Tk;
  689.      my $main = new MainWindow;
  690.      my $label = $main->Label(-text => 'Hello World!');
  691.      my $button = $main->Button(-text => 'Quit',
  692.                                 -command => sub{exit});
  693.      $label->pack;  #no "my" necessary here
  694.      $button->pack; #or here
  695.      MainLoop;
  696.  
  697.  Considering the finite number of names (in particular the high probability
  698.  that a variable named $label or $button was used in one or more of the
  699.  extensions to perl that you may be using) it helps one's programming to use
  700.  strict; and declare variables yours alone with my. 
  701.  
  702.  James M. Stern points out that redundant my declarations are not simply
  703.  useless they can be dangerous as in the following script which will not work: 
  704.  
  705.      #!/usr/local/bin/perl -w
  706.      use strict;
  707.      use Tk;
  708.      my $main = new MainWindow;
  709.      my $label = $main->Label(-text => 'Hello World!');
  710.      my $main;   #WRONG: this $main overrides previous
  711.      my $button = $main->Button(-text => 'Quit', #will now fail
  712.                                 -command => sub{exit});
  713.      $label->pack;  
  714.      $button->pack; 
  715.      MainLoop;
  716.  
  717.  ______________________________________________________________________
  718.  
  719.  
  720.  
  721.  12.5. Is there a way to find out what is in my perl/Tk "PATH"? 
  722.  
  723.  Presuming this question is asking for a little more than the answer you get
  724.  when you type: 
  725.  
  726.      ls perl5/lib/Tk/*.pm
  727.  
  728.  there are ways to find out what gets EXPORTED by Tk.pm. Use a script like: 
  729.  
  730.      #!/usr/bin/perl
  731.      
  732.      use Tk;
  733.      require 'dumpvar.pl';
  734.      
  735.      dumpvar('Tk');
  736.  
  737.  or more succintly at the shell command prompt: 
  738.  
  739.      perl -e 'use Tk; require "dumpvar.pl"; dumpvar("Tk");'
  740.  
  741.  The advantage of using dumpvar over ls is that it gives you a brief summary of
  742.  all the arguments your widgets want. Note that the output is many lines and
  743.  you may wish to pipe through more or less. 
  744.  
  745.  If you wish to determine the Configuration options a given widget accepts (and
  746.  what the values are at a given point in a script) you may use the ->configure
  747.  method with no arguments to retrieve the list of lists, as in this example: 
  748.  
  749.      #!/usr/bin/perl
  750.      
  751.      use Tk;
  752.      my $main = MainWindow -> new;
  753.      my $scrl = $main -> Scrollbar('-orient' => 'horizontal');
  754.  
  755.      @scrollconfig = $scrl -> configure;
  756.      for (@scrollconfig) {
  757.          print "@$_\n";
  758.      }
  759.      
  760.      etc.
  761.  
  762.  Such code is useful for development but is probably best left out, commented
  763.  out, or switched out of "production line" code. 
  764.  
  765.  ______________________________________________________________________
  766.  
  767.  
  768.  
  769.  12.6. What is the difference between use and require? 
  770.  
  771.  The short answer is that something like: 
  772.  
  773.      use Tk;
  774.  
  775.  is equivalent to: 
  776.  
  777.      BEGIN { require "Tk.pm"; import Tk; }
  778.  
  779.  Hence the essential difference is that a mere require Tk; does not achieve
  780.  the import of function/method names. The significance of this is that it
  781.  allows one to call ->Button rather than having to call the fully qualified 
  782.  ->Tk::Button e.g.. For further details on this subject see man perlmod(1)
  783.  or see Tom Christiansen's document at: 
  784.  
  785.      ftp://ftp.perl.com/perl/info/everything_to_know/use_vs_require
  786.  
  787.  ______________________________________________________________________
  788.  
  789.  
  790.  
  791.  12.7. How do I change the cursor/color? 
  792.  
  793.  Nick Ing-Simmons <nik@tiuk.ti.com> and others posted a series of answers
  794.  to this type of question. In summary what they said was: 
  795.  
  796.   Basically 
  797.  
  798.      $mw->configure(-cursor => ... );
  799.  
  800.   Unless you use one of built-in cursors it gets messy. 
  801.  
  802.   Here copy of what Tk/demos/color_editor does: 
  803.  
  804.      #!/usr/local/bin/perl -w
  805.      use Tk;
  806.      my $mw = MainWindow->new;
  807.      $mw->configure(-cursor => ['@' . Tk->findINC('demos/images/cursor.xbm'), 
  808.                                      Tk->findINC('demos/images/cursor.mask'),
  809.                                       'red', 'green']);
  810.      MainLoop;
  811.  
  812.   That says that argument to -cursor is a list of 4 things: 
  813.  
  814.   1. . Pathname to bitmap with '@' prepended to say it isn't a built in name
  815.     (Using findINC to locate file relative to Tk install location.) 
  816.   2. . Pathname to mask bitmap (no @ required) 
  817.   3. . Foreground colour 
  818.   4. . Background colour 
  819.  
  820.  
  821.  ! I want to remap it for the MainWindow
  822.  ! and will be using a pixmap.
  823.  
  824.   You won't be using a Pixmap with normal X11. X11 allows *bitmap*
  825.   with optional mask (another bitmap), and two colours. 
  826.  
  827.   The optional nature of the mask means that a simple call with a list
  828.   reference like: 
  829.  
  830.      $mw->configure(-cursor => ['watch', 'red', 'blue']);
  831.  
  832.   should work alright. 
  833.  
  834.  You may also obtain the value of the default cursor for a widget using
  835.  something like ->optionGet. 
  836.  
  837.  ______________________________________________________________________
  838.  
  839.  
  840.  
  841.  12.8. How do I ring the bell? 
  842.  
  843.  The short answer is 
  844.  
  845.     $widget -> bell;
  846.  
  847.  A slightly longer answer might include a fully functioning script: 
  848.  
  849.      #!/usr/bin/perl
  850.      use Tk;
  851.      $main = MainWindow -> new;
  852.      $butn = $main->Button(-text => 'bell')
  853.      $butn->configure(-command => sub{ $butn->bell; });
  854.      $butn->pack();
  855.      MainLoop;
  856.  
  857.  An even longer answer would be a fully functioning script with a callback: 
  858.  
  859.      #!/usr/bin/perl
  860.      use Tk;
  861.      $main = MainWindow -> new;
  862.      $but = $main->Button(-text => 'bell', 
  863.                           -command => sub{ringit($main)})->pack;
  864.      MainLoop;
  865.      
  866.      sub ringit { 
  867.          my $m = shift; 
  868.          $m->bell; 
  869.      }
  870.  
  871.  Simon Galton <galtons@candu.aecl.ca> reminds us to be careful in that 
  872.  
  873.   some systems remap this [the "console bell"] to anything from a digital
  874.   sound to a flash on the screen. 
  875.  
  876.  ______________________________________________________________________
  877.  
  878.  
  879.  
  880.  12.9. How do I determine the version of perl/Tk that I am running? 
  881.  
  882.  With an up to date perl installation one may query the local perl setup and all
  883.  extensions via the command: 
  884.  
  885.      perldoc perllocal
  886.  
  887.  For the Tk extension: version numbering has changed recently and
  888.  determining the version of perl/Tk that you are running now depends on what
  889.  version you are running: 
  890.  
  891.  Tk-b10++:
  892.  Tk-b10 (and higher) has changed to $Tk::VERSION (rather than the older "
  893.  $Tk:Version") to be consistent with other packages. Hence a short succinct
  894.  way to tell which version you have installed (that works with Tk-b11 and
  895.  Tk400.200) is: 
  896.  
  897.      perl -MTk -e 'print $Tk::VERSION."\n"'
  898.  
  899.  Tk-b9.01:
  900.  The version numbers as of Tk-b9.01 are stored in the following variables: 
  901.  
  902.      Core Tk version : $Tk::version
  903.      Tk patchLevel :   $Tk::patchLevel
  904.      library :         $Tk::library
  905.      perl/Tk Version : $Tk::Version 
  906.  
  907.  At your shell prompt you could say something like the following to determine
  908.  you perl/Tk Version: 
  909.  
  910.      perl -e 'use Tk; print "$Tk::Version\n";'
  911.  
  912.  The switch to Tk-b9.01 from previous versions included a large number of
  913.  method name changes. Nick was kind enough to include a b9names script in
  914.  the distribution that assists with the job of updating your older scripts. See the 
  915.  b9names script for a rather complete discussion of the name changes.
  916.  Geoffroy Ville also posted a notice of some of the changes. Here is a brief (and
  917.  very incomplete!) summary: 
  918.  
  919.  
  920.  older                         Tk-b9.01++
  921.  packslaves                    pack('slaves')
  922.  packpropagate                 pack('propagate')
  923.  packForget                    pack('forget')
  924.                                pack('info')
  925.  
  926.  $w->delete if ($w);            $w->destroy if ($w);
  927.  
  928.  Tk-b8(--):
  929.  A little script (Tk_module) can tell you and return the value: 
  930.  
  931.      #!/usr/bin/perl
  932.      use Tk;
  933.      local(*Tk_m) = \$Tk::Tk_module;
  934.      print "$Tk_m\n";
  935.  
  936.  Or more succintly say something like the following (at your shell prompt): 
  937.  
  938.      perl -e 'use Tk; print "$Tk::Tk_module\n";'
  939.  
  940.  You can obtain the version of Tk in use with the following (at your shell
  941.  prompt): 
  942.  
  943.      perl -e 'use Tk; print "$Tk::tk_version\n";'
  944.  
  945.  where this command returned "4.0" when the previous one (or Tk_module)
  946.  returned "b8". 
  947.  
  948.  All Tk versions:
  949.  Don't forget that you can always determine your Perl version/patchlevel/etc.
  950.  with: 
  951.  
  952.      perl -v
  953.  
  954.  (at the shell prompt - it's actually a little harder to get as much information
  955.  from within a #!script.) As of perl 5.002 you can use perl -V to determine
  956.  your perl Configuration. 
  957.  
  958.  OZAWA Sakuro <ozawa@prince.pe.u-tokyo.ac.jp> points out some ways to
  959.  do it in a script: 
  960.  
  961.   1. '$]' holds the version number. 
  962.   2. In Perl5, 'require NUMBER;' will complain if version is younger
  963.     than NUMBER. (e.g. require 5.001;) 
  964.   3. Of course, newly imported (and incompatible) features in newer
  965.     scripts will bailout before execution if parsed by an old interpreter. 
  966.  
  967.  Note that if you use English; then $PERL_VERSION holds the version
  968.  number. 
  969.  
  970.  To determine your MakeMaker version number try something like this
  971.  (5.002): 
  972.  
  973.      perl -MExtUtils::MakeMaker -e 'print "$ExtUtils::MakeMaker::VERSION\n";'
  974.  
  975.  or this (5.001m ok): 
  976.  
  977.      perl -e 'use ExtUtils::MakeMaker;print"$ExtUtils::MakeMaker::VERSION\n";'
  978.  
  979.  or even this (older perls and MakeMakers): 
  980.  
  981.      perl -e 'use ExtUtils::MakeMaker;print"$ExtUtils::MakeMaker::Version\n";'
  982.  
  983.  Please note that thoughout this FAQ document there are references to things
  984.  like Tk-b10(++) or Tk-b10++ which roughly translated to use English;
  985.  means something like "I think this will work with this version of Tk and
  986.  (maybe) higher versions...". You might also see Tk-b8(--) which means
  987.  something like "it worked with that old version and probably worked with
  988.  prior versions and if you are stuck with an old Tk version you might have to do
  989.  it this way...". 
  990.  
  991.  ______________________________________________________________________
  992.  
  993.  
  994.  
  995.  12.10. How do I call perl from C? 
  996.  
  997.  You need to see a recent copy of the perlembed(1) pod page. By "recent" it
  998.  needs to be up to date with at least perl5.002. 
  999.  
  1000.  Borrowing from Jon Orwant's preamble to that document: 
  1001.  
  1002.  Do you want to: 
  1003.  
  1004.  Use C from Perl?
  1005.     Read (at least) the perlcall(1), the perlapi(1), the perlxs(1),
  1006.     the perlxstut(1), and the perlguts(1) manpages.
  1007.  Use C++ from Perl?
  1008.     Recent changes to MakeMaker will make this easier. Be sure you are
  1009.     familiar with the perlcall(1), the perlapi(1), the perlxs(1),
  1010.     the perlxstut(1), and the perlguts(1) manpages.
  1011.  Use an executable program from Perl?
  1012.     Read about backquotes ``, system(), and exec() built in perl
  1013.     functions. Try reading the perlfunc(1) manpage.
  1014.  Use Perl from Perl?
  1015.     Read about do, eval, use and require. The perlfunc(1) manpage
  1016.     discusses these. For complete scripts you may also make use of the
  1017.     backquotes ``, system(), or exec() built in perl functions, but you
  1018.     may take a performance hit in doing so (see perlfunc(1) for
  1019.     information).
  1020.  Use C from C?
  1021.     Rethink your design.
  1022.  Use C++ from C++?
  1023.     See previous.
  1024.  Use Perl from C?
  1025.     Read (at least) the perlembed(1) and the perlguts(1) manpages.
  1026.  Use Perl from C++?
  1027.     Read (at least) the perlembed(1) and the perlguts(1) manpages.
  1028.  
  1029.  There is also an Doug MacEachern's <dougm@osf.org> embedder's
  1030.  development kit on CPAN and at a URL of the following form: 
  1031.  
  1032.      http://www.osf.org/~dougm/perl/Devel-embed-*.tar.gz
  1033.  or
  1034.      http://www.perl.com/cgi-bin/cpan_mod?module=ExtUtils::embed
  1035.  
  1036.  ______________________________________________________________________
  1037.  
  1038.  
  1039.  
  1040.  12.11. How do I call Tcl code from perl/Tk? 
  1041.  
  1042.  Assuming that you have a pressing need to call Tcl from perl/Tk then one
  1043.  "official way" to so would be via the ->send() and the ->Receive()
  1044.  methods. 
  1045.  
  1046.  It is also worth noting that you can still have access to a complete Tcl script
  1047.  from perl via the perl system, or `` (backtick), or even exec mechanisms.
  1048.  Just be careful with I/O waits and return values if you try one of these
  1049.  approaches. Further suggestions may be found in the various perlipc files at:
  1050.  
  1051.      ftp://ftp.perl.com/perl/info/everything_to_know/
  1052.  
  1053.  A more satisfactory Tcl/Tk-wish-like behavior can be embedded in perl by
  1054.  making appropriate modifications to Dov Grobgeld's perl script that uses
  1055.  sockets for perl<->wish communication: 
  1056.  
  1057.  #!/usr/local/bin/perl
  1058.  #####################################################################
  1059.  #  An example of calling wish as a subshell under Perl and
  1060.  #  interactively communicating with it through sockets.
  1061.  #
  1062.  #  The script is directly based on Gustaf Neumann's perlwafe script.
  1063.  #
  1064.  #  Dov Grobgeld dov@menora.weizmann.ac.il
  1065.  #  1993-05-17
  1066.  #####################################################################
  1067.  
  1068.      $wishbin = "/usr/local/bin/wish";
  1069.  
  1070.      die "socketpair unsuccessful: $!!\n" unless socketpair(W0,WISH,1,1,0);
  1071.      if ($pid=fork) {
  1072.              select(WISH); $| = 1;
  1073.              select(STDOUT);
  1074.  
  1075.          # Create some TCL procedures
  1076.              print WISH 'proc echo {s} {puts stdout $s; flush stdout}',"\n";
  1077.  
  1078.          # Create the widgets
  1079.          print WISH <<TCL;
  1080.          # This is a comment "inside" wish
  1081.  
  1082.          frame .f -relief raised -border 1 -bg green
  1083.          pack append . .f {top fill expand}
  1084.  
  1085.          button .f.button-pressme -text "Press me" -command {
  1086.              echo "That's nice."
  1087.          }
  1088.          button .f.button-quit -text quit -command {
  1089.              echo "quit"
  1090.          }
  1091.          pack append .f .f.button-pressme {top fill expand} \\
  1092.                         .f.button-quit {top expand}
  1093.  TCL
  1094.          # Here is the main loop which receives and sends commands
  1095.          # to wish.
  1096.          while (<WISH>) {
  1097.              chop;
  1098.              print "Wish sais: <$_>\n";
  1099.              if (/^quit/) { print WISH "destroy .\n"; last; }
  1100.          }
  1101.              wait;
  1102.      } elsif (defined $pid) {
  1103.          open(STDOUT, ">&W0");
  1104.          open(STDIN, ">&W0");
  1105.          close(W0);
  1106.          select(STDOUT); $| = 1;
  1107.          exec "$wishbin --";
  1108.      } else {
  1109.          die "fork error: $!\n";
  1110.      }
  1111.  
  1112.  Ilya Zakharevich <ilya@math.ohio-state.edu> has a "ptcl.h" header file for
  1113.  the construction of tcl bindings from pTk (there are limitations to this
  1114.  approach). It was posted to the mailing list archive at: 
  1115.  
  1116.      http://sun20.ccd.bnl.gov/~ptk/archive/ptk.1995.11/0057.html
  1117.  
  1118.  If you absolutely must pass large amounts of pre-parsed data between Tcl and
  1119.  perl then perhaps you should look into Malcolm Beattie's Tcl/Tk extensions to
  1120.  Perl instead. Those modules are distrubuted at CPAN sites. As mentioned
  1121.  above running Tcl/Tk/perl is incompatible with running perl/Tk. 
  1122.  
  1123.