start page | rating of books | rating of authors | reviews | copyrights

Book HomeMastering Perl/TkSearch this book

8.6. Inserting Text

Now that we've gone over text indexes and marks, we can talk in more detail about the methods for manipulating the widget's contents.

As we've seen from the many examples in this chapter, we use insert to put text into the Text widget. The first argument is an index and indicates where the text will be inserted. The second argument is the string to insert. The next argument (which is optional) is a single tag name or a reference to an array of tag names to assign to the inserted text. The usage is:

$text->insert(index, string, [ taglist, string, taglist ...] )

So far we've seen only single tags used with insert. If you want to specify more than one tag, put the tag names into square brackets, creating an anonymous array:

$t->insert('end', "This is a very tagged line", 
           [ 'tag1', 'tag2', 'tag3' ]);

To use different sets of tags, supply additional text lines and additional tag lists:

$t->insert('end', "This is the heading", ['heading', 'underline'],
                  "Second line", ['bold', 'blue']);

When you use the insert command to insert more than one set of text with different tags, make sure they always come in pairs: text, tags, text, tags, and so on. If the tag used isn't defined (with tagConfigure), there will be no effect on the text, but the tag will still be assigned to that text. You can create the tag later if you wish.

You can also insert an entire newline-delimited file with a single insert call:

{
    local $/ = undef;
    $text->insert('1.0', <FILE_HANDLE>);
}

We set the input record separator to undef, so the entire file is slurped as a single string.

8.6.1. Inserting Lines Using print and printf

The Perl/Tk Text widget also has built-in TIEHANDLE methods for print and printf. This means that prints to file handles tied to a Text widget invoke these special subroutines. The subroutines then insert the print arguments into the Text widget.

The following example uses print and printf to insert lines into a Text widget (Figure 8-5 illustrates):

#!/usr/local/bin/perl -w
use POSIX 'acos';
use Tk;
use strict;

my $mw = MainWindow->new;
my $text = $mw->Text(qw/-width 40 -height 10/)->pack;

tie *STDOUT, ref $text, $text;

print "Hello Text World!\n";
printf "pi ~= %1.5f", acos(-1.0);

MainLoop;
Figure 8-5

Figure 8-5. Lines inserted via print and printf



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.