Hello.
I thought getter, setter method will avoid this trouble.
Below was my trial. MyTieFile.pm
package MyTieFile;
use strict; use warnings;
use Tie::File;
use Encode qw/encode decode/;
use Carp;
my @Tied;
sub new {
my $class=shift;
my $filename=shift;
my %args =@_;
my %self;
$self{filename}=$filename;
if( exists($args{discipline}) ){
$self{encode}=$args{discipline};
if( $self{encode} =~ /\((.*)\)/){
$self{encode}=$1;
}
delete $args{discipline};
}
tie(@Tied, 'Tie::File', $filename, %args)
or confess 'tie @Tied failed';
return bless(\%self, $class);
}
sub get{
my $self=shift;
my $idx=shift;
return $self->{encode} ?
decode($self->{encode}, $Tied[$idx]) :
$Tied[$idx];
}
sub set{
my $self=shift;
my $idx=shift;
my $val=shift;
$Tied[$idx]= $self->{encode} ?
encode($self->{encode}, $val) :
$val;
}
sub max_index{
my $self=shift;
return $#Tied;
}
sub DESTROY {
my $self=shift;
untie $self->{filename};
}
1;
And test script
use strict;
use warnings;
use utf8;
use 5.012;
use feature qw< unicode_strings>;
use MyTieFile;
binmode STDOUT, ':unix:utf8';
my $t=MyTieFile->new('087.txt',recsep => "\x0D\x0A", discipline => ':e
+ncoding(UTF-8)');
my $i;
$i =0;
while (<DATA>) {
chomp;
$t->set( $i, $_);
++$i;
} # end while (<DATA>)
$i =0;
foreach ( 0 .. $t->max_index) {
say "$i ".$t->get($i);
++$i;
} # end foreach (@Tied)
__DATA__
.. pasted UTF8 text from stackoverflow ... I wish perlmonk support UTF
+-8 characters.
And I saw your post. So, overriding STORE,FETCH seems more elegant. I tried your untested code but it seems producing same warnings message for utf8 characters.
Why???
This seems to be a known problem because there is stackoverflow thread and I see the name "ikegami"
I hope "ikegami" or someone explains this problem , a little more...
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|