Kuang  Lu
Kuang Lu

Reputation: 51

get an empty array when using tie::file in perl

I tried to use Tie::File in perl to access files by writing a small piece of code. However, the "T_array" I got by running the code below seems to be empty:

#!/usr/bin/perl -w 
use strict;
use warnings;
use Tie::File;


my @T_array;
my $input3_file_name="/test/QtermsSorted.txt";##"newQurls";
tie @T_array, 'Tie::File', $input3_file_name|| die "Could not open $input3_file_name\n";
my $len=scalar(@T_array);
print "$len\n";
##print "$T_array[0]";
##untie @T_array;

The out put of it is 0, which means the array is empty. The "QtermsSorted.txt" is generated by perl under Linux. First, I though it might be the file coding issue and I tried to use "iconv -t utf8 QtermsSorted.txt" to change the coding, but it did not work. However, when I used a txt file created in Windows 8, the out put size was correct. I wonder whether you may tell me what is wrong and how to fix it. Thank you in advance.

Upvotes: 0

Views: 189

Answers (1)

Joel Berger
Joel Berger

Reputation: 20280

TL;DR: Always use or die ...

One thing I see is that your || die ... won't ever fire. It is a precedence problem. What gets executed is

tie @T_array, 'Tie::File', ($input3_file_name|| die "Could not open $input3_file_name\n");

and what you mean is

tie( @T_array, 'Tie::File', $input3_file_name )|| die "Could not open $input3_file_name\n";

if you change from || or or you will get the result you mean. Also you should add $! to the error string, so that you can see the error.

tie @T_array, 'Tie::File', $input3_file_name or die "Could not open $input3_file_name: $!\n";

Hopefully then you will get some reason as to why the tie is failing.

Upvotes: 2

Related Questions