【问题标题】:Perl not writing to a file in Windows 10Perl 未写入 Windows 10 中的文件
【发布时间】:2020-11-22 12:19:36
【问题描述】:

我有一个在 Server 2008 上编写的 Perl 脚本。在这里可以正常工作。

我已将其复制到我的笔记本电脑上,该笔记本电脑运行的是 Windows 10 家庭版,版本 1993,OS Build 18362.959。

我也是第一次下载 Active Perl。

该脚本基本上采用输入文件并将正则表达式应用于内容,然后将结果输出到文件。

在 Windows 10 上,它没有写入文件,甚至没有创建文件。

我已经对这个问题进行了搜索,但没有找到解决方案。

我尝试了下面的代码,在同一问题的回复上找到了一个。但它不会创建或写入文件。它在服务器 2008 上运行良好。我错过了什么吗? 如前所述,这是我第一次下载 ActivePerl 版本


Perl 版本详情如下:

This is perl 5, version 28, subversion 1 (v5.28.1) built for MSWin32-x64-multi-thread
(with 1 registered patch, see perl -V for more detail)

Copyright 1987-2018, Larry Wall

Binary build 0000 [58a1981e] provided by ActiveState http://www.ActiveState.com
Built Apr 10 2020 17:28:14

Perl 代码如下:

use strict;

use IO::File;   
my $FileHandle = new IO::File;

$FileName = "C:\\Users\\moons\\Documents\\Personal Planning\\Shopping\\ShoppingList.txt";

open ($FileHandle, "<$FileName") || print "Cannot open $FileName\n";

local $/;
 
my $FileContents  = <$FileHandle>;
close($FileHandle);

$FileContents =~ s/(Add|Bad|Limit|Each).*\n|Add$|\nWeight\n\d{1,}\nea|\$\d{1,}\.\d\d\/100g\n//g;
 Do more Regular expressions.
$FileContents =~ s/(.*)\n(.*)\n(\$\d{1,}\.\d\d)/$1,$3,$2/g;

printf $FileContents;

以上代码有效。下面的代码不会创建或写入文件。 $OutFile = "C:\Users\moons\Documents\Personal Planning\Shopping\test.txt";

$FileHandle = new IO::File;

open ($FileHandle, ">$OutFile") || print "Cannot open $OutFile\n";

printf $FileHandle $FileContents;
close($FileHandle);

【问题讨论】:

  • "以上代码有效。" - 我对此表示怀疑。它甚至无法编译,因为$FileHandle 没有包名,myour 等....Edit 问题并包含一个(可编译的)minimal reproducible example
  • 发现问题。它与代码无关。我的笔记本电脑上安装了 Comodo。 Comodo 正在对脚本生成的文件进行自动包含。它将文件放入 C 驱动器上的隐藏文件夹中。我更新了自动包含设置以允许 Perl 写入 require 文件夹。一旦我这样做了,文件就会在文件夹中创建。

标签: windows file perl write


【解决方案1】:

始终使用use strict; use warnings;

my $OutFile = "C:\Users\moons\Documents\Personal Planning\Shopping\test.txt";

结果

Unrecognized escape \m passed through at a.pl line 3.
Unrecognized escape \D passed through at a.pl line 3.
Unrecognized escape \P passed through at a.pl line 3.
Unrecognized escape \S passed through at a.pl line 3.

你可以使用

my $OutFile = "C:\\Users\\moons\\Documents\\Personal Planning\\Shopping\\test.txt";

整件事:

use strict;
use warnings;

my $in_qfn  = "C:\\Users\\moons\\Documents\\Personal Planning\\Shoppin\\ShoppingList.txt";
my $out_qfn = "C:\\Users\\moons\\Documents\\Personal Planning\\Shopping\\test.txt";

open(my $in_fh, '<', $in_qfn)
   or die("Can't open \"$in_qfn\": $!\n");
open(my $out_fh, '>', $out_qfn)
   or die("Can't create \"$out_qfn\": $!\n");

my $file;
{
   local $/;
   $file = <$in_fh>;
}

for ($file) {
   s/(Add|Bad|Limit|Each).*\n|Add$|\nWeight\n\d{1,}\nea|\$\d{1,}\.\d\d\/100g\n//g;
   s/(.*)\n(.*)\n(\$\d{1,}\.\d\d)/$1,$3,$2/g;
}

print $file;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 2011-02-06
    相关资源
    最近更新 更多