Search code examples
perlfilebioperl

Using command line argument as a file name in perl


The following perl script takes an argument from the command line and use that as the output file name.

my $str = $ARGV[0];
my $out_handler= Bio::SeqIO->new(
    -file => $str,
    -format => 'Fasta'
);

It is similar to this example. while I run perl test.pl polg, I get this error

------------- EXCEPTION -------------
MSG: Could not read file 'polg': No such file or directory
STACK Bio::Root::IO::_initialize_io /opt/perl/lib/site_perl/5.14.2/Bio/Root/IO.pm:268
STACK Bio::SeqIO::_initialize /opt/perl/lib/site_perl/5.14.2/Bio/SeqIO.pm:513
STACK Bio::SeqIO::fasta::_initialize /opt/perl/lib/site_perl/5.14.2/Bio/SeqIO/fasta.pm:87
STACK Bio::SeqIO::new /opt/perl/lib/site_perl/5.14.2/Bio/SeqIO.pm:389
STACK Bio::SeqIO::new /opt/perl/lib/site_perl/5.14.2/Bio/SeqIO.pm:435
STACK toplevel test.pl:16
-------------------------------------

How can I fix that?


Solution

  • Your program is trying to read from that file and failing because it doesn't exist

    Your example code on github has this

    -file => '>chrom20.fasta'
    

    so I suggest you should try

    -file => ">$str"
    

    or you can run your program as

    perl test.pl >polg
    

    Also, I'm sure you can think of a better name than $str for a scalar variable containing an output file name. $str is only fractionally better than $var