[英]Why I can not open files to read or write in perl?
我正在使用 vs 代碼學習 Perl。 我正在嘗試打開 file.pep 並從中讀取,但每次我發現找不到路徑。 我已將 protein.pep 和 code.pl 放在同一個文件夾中。
這是 protein.pep 文件
MNIDDKLEGLFLKCGGIDEMQSSRTMVVMGGVSGQSTVSGELQD
SVLQDRSMPHQEILAADEVLQESEMRQQDMISHDELMVHEETVKNDEEQMETHERLPQ
GLQYALNVPISVKQEITFTDVSEQLMRDKKQIR
使用路徑 D:\bioinformatics\protein.pep
這是我的 code.pl 文件
#!/usr/bin/perl -w
$proteinfilename = 'protein.pep';
open(PROTEINFILE, $proteinfilename)or die "Can't open '$seq': $!";
# First line
$protein = <PROTEINFILE>;
# Print the protein onto the screen
print "\nHere is the first line of the protein file:\n\n";
print $protein;
# Second line
$protein = <PROTEINFILE>;
# Print the protein onto the screen
print "\nHere is the second line of the protein file:\n\n";
print $protein;
# Third line
$protein = <PROTEINFILE>;
# Print the protein onto the screen
print "\nHere is the third line of the protein file:\n\n";
print $protein;
它的路徑是 D:\bioinformatics\code.pl
我得到這個 output “系統找不到指定的路徑。”
您的代碼中有:
$proteinfilename = 'protein.pep';
open(PROTEINFILE, $proteinfilename)or die "Can't open '$seq': $!";
首先,更改錯誤消息以告訴您open
需要哪個文件:
open(PROTEINFILE, $proteinfilename) or die "Can't open '$proteinfilename': $!";
你只給open
相對路徑名。 我敢打賭它適用於完整的路徑名:
$proteinfilename = 'D:\\bioinformatics\\protein.pep';
open(PROTEINFILE, $proteinfilename) or die "Can't open '$proteinfilename': $!";
如果您仍然有問題,請發布程序的實際 output。
我猜問題出在您的 IDE 和當前工作目錄上。 程序不會自動在您存儲它的目錄中運行。 您可以使用 Perl 隨附的Cwd
模塊來查看您的 IDE 從哪里開始:
use Cwd qw(getcwd);
print "I'm in " . getcwd() . "\n";
如果您希望程序在工作時位於特定目錄中,
chdir $some_directory or die "Could not change to '$some_directory': $!";
您可以選擇該目錄與程序的目錄相同。 Perl 附帶的FindBin
模塊可以方便地告訴您它在哪里:
use FindBin;
chdir $FindBin::Bin;
Perl 有各種更好的做事方式,盡管它幾乎支持你 30 年前可以做的所有事情。 表示文件模式的三個參數open
更安全一些。 而且, Perl v5.36 是關於在您指定use v5.36
時禁用用戶定義的裸字文件句柄,因此請養成使用詞法文件句柄的習慣。
open my $protein_fh, '<', $proteinfilename or die "Can't open '$proteinfilename': $!";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.