Perl:以连续的文件编号存储文件

问题描述 投票:0回答:1

我想打开一个 data(n).txt 文件(在已经存在 data(n).txt 文件的目录中:例如:data0001.txt、data0002.txt、data0003.txt) 在这个(新)文件中打印一些数据后,我想用连续的文件编号存储这个新文件(在本例中:data0004.txt) 我是初学者,对 Perl 不太了解

此代码仅创建 data0001.txt 文件并覆盖其内容

#!/usr/bin/perl    
open (DATEI, ">>data0001.txt") or die $!;
   print DATEI "this is a test";
close (DATEI);
perl sequential-number
1个回答
0
投票

为了按照所描述的方式命名一个文件,其数字比现有文件名中的最大数字大一,我们需要首先读取目录并找出文件名中的最大数字是多少。然后我们可以编写新文件,使用

sprintf
将数字格式化为文件名中的四字符字符串

一种方法来做到这一点

use warnings;
use strict;
use feature 'say';

use FindBin qw($RealBin);
use List::Util qw(max);

# Submit directory on the command line or use the one where this script is    
my $dir = shift // $RealBin;

my @files = glob "$dir/data*txt";

my $max_num = max map { /data([0-9]{4})\.txt/ } @files;

my $next_file_name = 'data' . sprintf("%04d", $max_num+1) . '.txt';

open my $fh, '>', $next_file_name or die "Can't open $next_file_name: $!";

say $fh "Writing to the next file $next_file_name";
close $fh or warn "Error writing to $next_file_name: $!"

文档,按出现顺序排列:[FindBin]

© www.soinside.com 2019 - 2024. All rights reserved.