Reputation: 37
I just wrote a very simple perl tk script to read a huge text file and display it with Text widget and attached it to Scrollbar widget. Now my problem is that each time i run the script , it displays from the first sentence ( of the whole text file ) onwards. How can i make the script remember my position in the text and display the same area when i quit and start the script again i.e if i read the 1000 th line of the text and quit the script, script should show the 1000th line onwards when i again run it. ( or in other words remember the scroll position)
I am not a professional in perl tk nor perl but trying my best to learn it. Please give a reply explaining it lucidly
Upvotes: 1
Views: 180
Reputation: 242443
If you close your perl script, it ends. It cannot remember anything, it's not there anymore. But, you can make the script to save the position to a file, and upon startup, you can try to read the position from the file. See the following example:
#!/usr/bin/perl
use warnings;
use strict;
use Tk;
my $file = 'input.txt';
my $config = '.viewtext.conf';
my $mw = MainWindow->new(-title => 'Remember Position');
my $t = $mw->Scrolled("Text", -scrollbars => 'se')->pack;
my $b = $mw->Button(-text => 'Quit', -command => \&quit)->pack;
open my $FH, '<', $file or die $!;
$t->Contents(<$FH>);
close $FH;
if (-f $config) {
open my $FH, '<', $config or die $!;
my ($x0, $x1, $y0, $y1) = split / /, <$FH>;
$t->xviewMoveto($x0); # Here we restore the saved position
$t->yviewMoveto($y0);
}
MainLoop();
sub quit {
open my $CONF, '>', $config or die $!;
print {$CONF} join ' ', $t->xview, $t->yview; # This is the current position
close $CONF;
$mw->destroy;
}
If you are going to open several different files, you have to remember the path to the file together with the position.
Upvotes: 2