cac*_*ano 0 windows directory perl
我有一个包含文本文件数据的数组.
我想过滤数组并将一些信息复制到另一个数组.grep好像不行.
这就是我所拥有的
$file = 'files.txt';
open (FH, "< $file") or die "Can't open $file for read: $!";
@lines = <FH>;
close FH or die "Cannot close $file: $!";
chomp(@lines);
foreach $y (@lines){
if ( $y =~ /(?:[^\\]*\\|^)[^\\]*$/g ) {
print $1, pos $y, "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
public_html
Trainings and Events
General Office\Resources
General Office\Travel
General Office\Office Opperations\Contacts
General Office\Office Opperations\Coordinator Operations
public_html\Accordion\dependencies\.svn\tmp\prop-base
public_html\Accordion\dependencies\.svn\tmp\props
public_html\Accordion\dependencies\.svn\tmp\text-base
Run Code Online (Sandbox Code Playgroud)
正则表达式应该使用最后一个或两个文件夹并将它们放入自己的数组中进行打印.
正则表达式可以对此非常挑剔.将路径拆分为组件然后根据需要进行计数要容易得多.并且有一个适合您的确切目的的工具,核心模块File::Spec,如xxfelixxx在评论中所提到的.
您可以使用它splitdir来分解路径,并catdir组成路径.
use warnings 'all';
use strict;
use feature 'say';
use File::Spec::Functions qw(splitdir catdir);
my $file = 'files.txt';
open my $fh, '<', $file or die "Can't open $file: $!";
my @dirs;
while (<$fh>) {
next if /^\s*$/; # skip empty lines
chomp;
my @all_dir = splitdir $_;
push @dirs, (@all_dir >= 2 ? catdir @all_dir[-2,-1] : @all_dir);
}
close $fh;
say for @dirs;
Run Code Online (Sandbox Code Playgroud)
我使用模块的功能界面,而对于较重的工作,你需要它的面向对象.将整个文件读入数组有其用途,但一般是逐行处理.列表操作可以更优雅地完成,但我只是为了简单.
我想补充一些一般性意见
始终使用use strict和启动您的程序use warnings
使用词法文件句柄,my $fh而不是FH
了解(至少)十二个或两个最常用的模块真的很有帮助.例如,在上面的代码中,我们甚至不必提及分隔符\.
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |