7

I wanted to choose what data to put into which file depending on the index. However, I seem to be stuck with the following.

I have created the files using an array of file handles:

my @file_h;
my $file;
foreach $file (0..11)
{
    $file_h[$file]= new IT::File ">seq.$file.fastq";
}

$file= index;
print $file_h[$file] "$record_r1[0]$record_r1[1]$record_r1[2]$record_r1[3]\n";

However, I get an error for some reason in the last line. Help anyone....?

2
  • This is an oddity of Perl's syntax, since filehandles weren't originally even variables, much less more complicated lvalues. Commented Jun 3, 2012 at 2:26
  • What is the error? Also, could you contrive a complete, self contained example? (That would answer some immediate questions like, do you really mean IT::File [sic]? Do you mean index() or $index?) Commented Jun 3, 2012 at 21:18

3 Answers 3

20

That should simply be:

my @file_h;
for my $file (0..11) {
    open($file_h[$file], ">", "seq.$file.fastq")
       || die "cannot open seq.$file.fastq: $!";
}

# then later load up $some_index and then print 
print { $file_h[$some_index] } @record_r1[0..3], "\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly flock $file_h[$some_index],LOCK_EX works without brackets. Does anyone know why? What is exactly a filehandle in perl?
5

You can always use the object-oriented syntax:

$file_h[$file]->print("$record_r1[0]$record_r1[1]$record_r1[2]$record_r1[3]\n");

Also, you can print out the array more simply:

$file_h[$file]->print(@record_r1[0..3],"\n");

Or like this, if those four elements are actually the whole thing:

$file_h[$file]->print("@record_r1\n");

Comments

1

Try assigning the $file_h[$file] to a temporary variable first:

my @file_h;
my $file;
my $current_file;

foreach $file (0..11)
{
    $file_h[$file]= new IT::File ">seq.$file.fastq";
}

$file= index;
$current_file = $file_h[$file];

print $current_file "$record_r1[0]$record_r1[1]$record_r1[2]$record_r1[3]\n";

As far as I remember, Perl doesn't recognize it as an output handle otherwise, complaining about invalid syntax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.