以下是20个常用的Perl脚本示例:

  1. 计算数组元素的总和:
my @numbers = (1, 2, 3, 4, 5);
my $sum = 0;
foreach my $num (@numbers) {
    $sum += $num;
}
print "Sum: $sum\n";
  1. 解析命令行参数并打印输出:
my $name = $ARGV[0];
print "Hello, $name!\n";
  1. 读取文件内容并打印每行:
open(my $fh, "<", "filename.txt") or die "Cannot open file: $!";
while (my $line = <$fh>) {
    print $line;
}
close($fh);
  1. 使用正则表达式替换文本:
my $text = "This is a sample text.";
$text =~ s/sample/example/;
print "$text\n";
  1. 处理CSV文件内容:
use Text::CSV;
my $csv = Text::CSV->new();

open(my $fh, "<", "data.csv") or die "Cannot open file: $!";
while (my $row = $csv->getline($fh)) {
    # 处理CSV行数据
    my $name = $row->[0];
    my $age = $row->[1];
    print "$name is $age years old.\n";
}
close($fh);
  1. 生成随机数:
my $random_number = int(rand(100));
print "Random number: $random_number\n";
  1. 获取系统时间:
use POSIX qw(strftime);
my $current_time = strftime '%Y-%m-%d %H:%M:%S', localtime;
print "Current time: $current_time\n";
  1. 执行系统命令并获取输出:
my $output = `ls -l`;
print "Listing:\n$output";
  1. 计算字符串长度:
my $str = "Hello, World!";
my $length = length($str);
print "Length of string: $length\n";
  1. 判断文件是否存在:
my $filename = "file.txt";
if (-e $filename) {
    print "$filename exists.\n";
} else {
    print "$filename does not exist.\n";
}
  1. 读取用户输入并进行处理:
print "Enter your name: ";
my $name = <STDIN>;
chomp($name);
print "Hello, $name!\n";
  1. 计算平方根:
my $number = 25;
my $sqrt = sqrt($number);
print "Square root of $number: $sqrt\n";
  1. 遍历哈希表并打印键值对:
my %hash = (
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
for my $key (keys %hash) {
    print "$key: $hash{$key}\n";
}
  1. 计算阶乘:
sub factorial {
    my $n = shift;
    return 1 if $n == 0;
    return $n * factorial($n-1);
}
my $result = factorial(5);
print "Factorial of 5: $result\n";
  1. 正向迭代和反向迭代数组元素:
my @array = (1, 2, 3, 4, 5);
foreach my $num (@array) {
    print "Forward: $num\n";
}
for (my $i = $#array; $i >= 0; $i--) {
    print "Reverse: $array[$i]\n";
}
  1. 递归遍历目录并输出文件列表:
sub list_files {
    my $dir = shift;
    opendir(my $dh, $dir) or die "Cannot open directory: $!";
    while (my $file = readdir($dh)) {
        next if $file eq '.' or $file eq '..';
        print "$file\n";
    }
    closedir($dh);
}
list_files(".");
  1. 计算字符串中单词的个数:
my $str = "Perl is a powerful scripting language.";
my @words = split(" ", $str);
my $word_count = scalar(@words);
print "Word count: $word_count\n";
  1. 生成日期范围:
use Date::Calc qw(:all);
my ($year, $month, $day) = Today();
my $start_date = Date_to_Text($year, $month, $day);
my $end_date = Add_Delta_YMD($year, $month, $day, 0, 1, 0);
print "Date range: $start_date - $end_date\n";
  1. 计算数组中元素的平均值:
my @numbers = (3, 5, 7, 9, 11);
my $sum = 0;
foreach my $num (@numbers) {
    $sum += $num;
}
my $average = $sum / scalar(@numbers);
print "Average: $average\n";
  1. 通过HTTP POST请求发送数据:
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $response = $ua->post('https://example.com/api', { key => 'value' });
if ($response->is_success) {
    my $content = $response->decoded_content;
    print "Response: $content\n";
} else {
    die "POST request failed: " . $response->status_line;
}

这些Perl脚本示例涵盖了文件处理、字符串操作、正则表达式、数组和哈希表操作、日期处理、网络操作等常见场景。

03-24 10:58