第一次用perl,简单了解下语法,好难记,不过既然perl能那么牛逼的存在这么久,必然有其过人之处,如lcov就是用perl做得。因此还是有必要学习下,至少能达到看懂别人脚本的目的,装个window版尝个新鲜。
下载:http://strawberryperl.com/
尝鲜脚本:http://learn.perl.org/examples/read_write_file.html
遇到的问题:
1. use Path::Class; 失败,提示 "Error installing package 'Path-Class': Could not locate a PPD file for package Path-Class"
解决:尝试1)C:\strawberry\perl\bin>cpan Path::Class
尝试2)C:\strawberry\perl\bin>ppm.bat
PPM> install Path::Class
write.pl
#!/usr/bin/perl use strict; use warnings; use Path::Class; use autodie; # die if problem reading or writing a file my $dir = dir("."); # /tmp my $file = $dir->file("file.txt"); # /tmp/file.txt # Get a file_handle (IO::File object) you can write to my $file_handle = $file->openw(); my @list = ('a', 'list', 'of', 'lines'); foreach my $line ( @list ) { # Add the line to the file $file_handle->print($line . "\n"); }read.pl
#!/usr/bin/perl use strict; use warnings; use Path::Class; use autodie; # die if problem reading or writing a file my $dir = dir("."); # /tmp my $file = $dir->file("file.txt"); # Read in the entire contents of a file my $content = $file->slurp(); print $content; # openr() returns an IO::File object to read from my $file_handle = $file->openr(); # Read in line at a time while( my $line = $file_handle->getline() ) { print $line; }
补充些基本用法:
(用惯了c和python,perl的语法感觉很难用,补充些基本的语法操作先,做个记录)
#!/usr/bin/perl use strict; use warnings; print "数字相关运算及处理"; print 3.14 * 3.13; print "基本输入操作"; print "请输入\n"; my $val=<STDIN>; $val = chomp $val; print "您输入了【$val】"; print "列表和数组操作\n"; my @fred = qw{a b c}; print join ',', @fred; print "\n"; my @afred = qw# a b c #; print join ',', @afred; print "\n"; my @bfred = qw( a b c ); print @bfred; print "\n"; my @cfred = qw/ a b c /; print @cfred; print "\n"; my @array = 5..9; print pop(@array); print @array; print "\n"; push @array, 1..3; print @array; print "\n"; @array = 1..3; shift @array; print @array; print "\n"; unshift (@array, 0); print @array; print "\n"; @array = 1..10; my @r_array = reverse @array; print @r_array; foreach (1..6) { my $square = $_*$_; print "$_ squared is $square.\n"; } my @items = qw( wilma dino pebbles ); my $format = "The items are :\n". ("%10s\n" x @items); printf $format, @items; printf "The items are:\n", ("%10s\n" x @items), @items; my %some_hash = ("foo",35, "bar", 12.4, 2.5, "hello", "wilma", 1.72e30, "betty", "bye\n"); print %some_hash; print "\n"; my %last_name = ( "fred" => "flintstone", "dino" => "di", "barney" => "rubble", "betty" => "rubble" ); print %last_name; print "\n"; my %hash = ("a" => 1, "b" => 2, "c" => 3); my @k = keys %hash; my @v = values %hash; print %hash; print "\n"; print "打印hash的key\n"; print @k; print "\n"; print "打印hash的values\n"; print @v; $hash{"extra_key"} = "extra_val"; print "\n打印hash表元素\n"; while ((my $key, my $value) = each %hash) { print "$key => $value\n"; }