1

これを機能させることはできません。

#!/usr/bin/perl -w
use strict;
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
my $id='123456'; 
my $filetoopen = '/home/user/public/somefile.txt';

ファイルには以下が含まれます:

123456
234564
364899
437373

だから...他のサブとコードの束

if(-s $filetoopen){
     perl -n -i.bak -e "print unless /^$id$,/" $filetoopen;
}

ファイル $filetoopen から $id に一致する行を削除する必要があります

しかし、$id が $filetoopen にない場合でも、スクリプトが「クラッシュ」することは望ましくありません。

これは、コマンド ラインから実行されるのではなく、.pl スクリプトのサブにあります。

私は近いと思いますが、ここで何時間も読んだ後、質問を投稿することに頼らなければなりませんでした.

これはスクリプトでも機能しますか?

私は成功してTIEを試しましたが、代わりにTIE::FILEなしでこれを行う方法を知る必要があります。

試してみると、エラーが発生しました:

mylearningcurve.pl 行 456、「bak -e」付近の構文エラー

この老犬を教えてくれてありがとう...

4

3 に答える 3

2

First of all (this is not the cause of your problem) $, (aka $OUTPUT_FIELD_SEPARATOR) defaults to undef, I'm not sure why you are using it in the regex. I have a feeling the comma was a typo.

It's unclear if you are calling this from a shell script or from Perl?


If from Perl, you should not call a nested Perl interpreter at all.

If the file is small, slurp it in and print:

use File::Slurp;
my @lines = read_file($filename);
write_file($filename, grep { ! /^$id$/ } @lines);

If the file is large, read line by line as a filter.

use File::Copy;
move($filename, "$filename.old") or die "Can not rename: $!\n";
open(my $fh_old, "<", "$filename.old") or die "Can not open $filename.old: $!\n";
open(my $fh, ">", $filename) or die "Can not open $filename: $!\n";
while my $line (<$fh_old>) {
    next if $line =~ /^id$/;
    print $fh $_;
}
close($fh_old);
close($fh);

If from a shell script, this worked for me:

$ cat x1
123456
234564
364899
437373

$ perl -n -i.bak -e "print unless /^$id$/" x1

$ cat x1
234564
364899
437373
于 2012-05-11T13:20:52.437 に答える
0

コマンドライン引数の機能には、-iを介してアクセスできます$^I

local @ARGV = $filetoopen;
local $^I = '.bak';
local $_;
while (<>) {
   print if !/^$id$/;
}
于 2012-05-11T17:41:51.860 に答える
0
if(-s $filetoopen){
     perl -n -i.bak -e "print unless /^$id$,/" $filetoopen;
}

あなたがこれに何を期待しているのか、私にはまったくわかりません。コマンド ライン プログラムを Perl コードの途中に置くことはできません。system外部プログラムを呼び出すために使用する必要があります。Perl は、他のプログラムと同様に、単なる外部プログラムです。

if(-s $filetoopen){
     system('perl', '-n -i.bak -e "print unless /^$id$,/"', $filetoopen);
}
于 2012-05-11T14:41:20.643 に答える