gpt4 book ai didi

arrays - Perl - 如何从分隔的 txt 文件中读取每一行并处理它

转载 作者:太空狗 更新时间:2023-10-29 11:43:26 24 4
gpt4 key购买 nike

我有一个由“:”分隔的文本文件

它有3个字段

field-1-->文件名

field-2-->文件源路径

field-3-->文件的目标路径

例如。

helloWorld.txt:/home/abc:/home/xyz

现在我必须将这个文件 helloWorld.txt 从它的源路径复制到目标路径。

并且需要对文本文件中的所有可用行执行此操作。

我不确定我正在尝试的是最佳实践。但是它没有用。

有人可以告诉我完成这个的最佳方法吗?

非常感谢

    open FILE, $inputFile or die $!;
while(my $file_name=<FILE>)
{
my ($tmpvar1, $tmpvar2, $tmpvar3) = split(/:/, $_);
my $command = "cp ".$tmpvar2. "/". $tmpvar1 $tmpvar3;
exce $command;
}

最佳答案

使用有意义的变量名(不是 $tempvar)。一旦开始使用它们 ($file_name),请确保该变量确实包含其名称所暗示的内容(实际上并不包含)并在任何地方使用它(即,不要拆分 $_)。

要复制文件,请使用 File::Copy .从版本 5.002 开始,它随 Perl 一起提供。

缩进代码以提高可读性。

不要向 SO 发布会抛出语法错误的代码。

Scalar found where operator expected at /home/choroba/1.pl line 6, near "$tmpvar1 $tmpvar3"
(Missing operator before $tmpvar3?)

可能的修复:

#!/usr/bin/perl
use warnings;
use strict;

use File::Copy;

open my $IN, '<', $inputFile or die $!;
while (my $line = <$IN>) {
chomp $line;
my ($name, $source, $destination) = split /:/, $line;
copy("$source/$name", "$destination/$name")
or warn "Copying $name from $source to $destination failed: $!";
}

关于arrays - Perl - 如何从分隔的 txt 文件中读取每一行并处理它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31657019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com