MEhsan
MEhsan

Reputation: 2324

Reading data from a file using Perl

I have used the following code in perl to open and read a file contains protein data:

# !/usr/bin/perl -w

$proteinFileName = 'NM_021964fragment.pep';
open (PROTEINFILE, $proteinFileName);
$protein = <PROTEINFILE>;
close PROTEINFILE;

print "Here is the protein: \n";
print "$protein";
exit;

The problem that I am facing is that the provided code does not print out the data. The protein sequence data file 'NM_021964fragment.pep' is located in my desktop and even when I specified the location it does not read the file.

Any idea to get the code running?

Upvotes: 1

Views: 982

Answers (3)

AnFi
AnFi

Reputation: 10903

Your code reads first line of the file.
Use File::Slurp module to read whole file into variable OR try the code below.

# !/usr/bin/perl -w
use strict;
my $proteinFileName = 'NM_021964fragment.pep';
my $protein;
{ 
   local $/= undef;

   open (my $PROTEINFILE, '<', $proteinFileName) || die "Can't open";
   $protein = <$PROTEINFILE>;
   close $PROTEINFILE;
}

print "Here is the protein: \n";
print "$protein";
exit;

man perlvar :

$/ The input record separator, newline by default. [...] You may set it [...] to "undef" to read through the end of file.

Upvotes: 0

DarkHorse
DarkHorse

Reputation: 161

I think the problem may be caused by that your perl script is not in the same directory with you protein file. you can load two of them together and try again. if you want to input the path of file as a parameter, you can write like that below:

@ARGV==1 || die"please input the file path";
open(IN, $ARGV[0]) || die "can't open the file $ARGV[0]:$!";
$protein = <PROTEINFILE>; ##get one line once, if you want to get all information, use while loop or like this: @protein = <PROTEINFILE>;
##something you like to do
close(IN);

Upvotes: 1

SzG
SzG

Reputation: 12619

First print a diag message when open fails. This is the Perl-way to do it:

open PROTEINFILE, $proteinFileName or die $!;

Some questions:

  • What is the current working directory in which you start the Perl program?
  • In case of your above example, you should cd to the directory where the pep file is located.
  • Do you start the script from the command line?
  • Does this happen to be Cygwin-Perl on a Windows machine?

Next, the <> operator reads one line from a file. If the file has multiple lines and you want to read the whole file into a string, you need a loop to concatenate all lines into it:

$protein .= $_ while (<PROTEINFILE>);

Upvotes: 2

Related Questions