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

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

它有3个领域

字段1 – >文件的名称

field-2 – >文件的源path

字段3 – >文件的目标path

例如。

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

现在我必须从源path复制这个文件helloWorld.txt到目标path。

这需要为文本文件中的所有可用行完成。

我不知道我正在尝试的是最佳做法。 它没有工作。

有人可以告诉最好的方法来完成这个?

非常感谢

  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: $!"; } 
 use strict; use warnings; use File::Copy; open my $file, "<", $inputFile or die $!; while( my $line=<$file> ) { chomp $line; my ($tmpvar1, $tmpvar2, $tmpvar3) = split(/:/, $line); copy "$tmpvar2/$tmpvar1", $tmpvar3; } close $file; 

最佳做法是使用核心模块操作文件名和文件本身File :: * :

 #!/usr/bin/env perl use strict; use warnings; use File::Copy qw(cp); use File::Spec::Functions; while (<>) { chomp; ( my ( $name, $source, $destination ) = split /:/ ) == 3 or die "Broken data on line $.:$_\n"; -d $destination or die "Destination $destination doesn't exist.\n"; my $src = catfile( $source, $name ); cp( $src, $destination ) or die "Can't copy $src -> $destination\n"; }