Hi,

I have a GUI with a text window, in which I sometimes want to delete a chunk of text and insert different text in its place. I'm using something like this:
$text->delete($start_index,$end_index); $text->insert($start_index,$my_new_text);
(Both $start_index and $end_index always look like '###.0'.)

This works fine as long as $end_index is somewhere in the middle of the whole text. However, if $end_index is actually the same as 'end',
the new text isn't inserted after a newline, but rather at the end of the previous line.

Is there a way to prevent this? (Other than checking if I'm inserting text in the end, and then adding a newline myself...)

Here is a sample code that I wrote to demonstrate the problem:
use strict; use Tk; my $mw = MainWindow->new(); my $frame = $mw->Frame() ->pack(-side => "left", -expand => 1, -fill => 'both'); my $text = $frame->Scrolled('Text') ->pack(-expand => 1, -fill => 'both'); my $data; for (my $i = 1; $i < 20; $i++) { $data .= "abcdefghi $i \n"; } $text->insert('end',$data); my $but1 = $frame->Button(-text => "Replace in the middle", -command => [\&replace,$text,'3.0','7.0']) ->pack(-side => 'left'); my $but2 = $frame->Button(-text => "Replace in the end", -command => [\&replace,$text,'16.0','end']) ->pack(-side => 'left'); MainLoop(); sub replace { my ($text,$start_index,$end_index) = @_; my $old_data = $text->get($start_index,$end_index); $old_data =~ s/cdefg/12345/g; $text->delete($start_index,$end_index); $text->insert($start_index,$old_data); return; }
Thanks a lot!

In reply to Indices and inserts in Tk::Text by anna_black

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.