# Lesson3 - Spring 2010 1 Perl 入门和提高 Lesson 3...

This preview shows pages 1–2. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Spring, 2010 1 Perl 入门和提高 Lesson 3 周晓方 [email protected] Spring, 2010 2 Sample • @s 里面是一个 spice 文本，请把电容的容量加倍， 电阻的阻值减半；不考虑续行。 • 提示，电容卡的格式是 "C 名称 Node1 Node2 容量 " @s = ('RIN 1 2 10MEG', 'EGAIN 3 0 1 2 100K', 'RP1 3 4 1K', 'CP1 4 1.5915UF', 'ROUT 5 6 10'); s/^(C(\S+\s+){3})([0-9\.]+)/\$1.(\$3*2)/e foreach @s; /^R/ and s/([0-9\.]+)(\S*)\$/(\$1\/2).\$2/e foreach @s; print join "\n", @s; RIN 1 2 5MEG EGAIN 3 0 1 2 100K RP1 3 4 0.5K CP1 4 0 3.183UF ROUT 5 6 5 别忘了除法运算 符 / 要转 义 Spring, 2010 3 join, map, split, reverse, sort, grep join("\n", @array); # return string map("\$_\n", @array); # return array print join "\t", map \$_*\$_, 1..10; print join "\t", map int rand(20), 1..10; split(/pattern/, "string"); # return array @list = split(//, "ABCDEFGHI"); # qw(A B C D E F G H I) @list = split(/:/, "12:34:56:78", 3); # qw(12 34 56:78) reverse(@array); # return array 数组反 序 scalar reverse(@array); # 合并成字符串，字符反 序 %new_hash = reverse %old_hash;# 交换哈希表的 key 和 val sort(@array); # return array sort {\$a cmp \$b} @list; # 用法很丰富，参考 perlop sort {\$a <=> \$b} @list; sort {-(\$a <=> \$b)} @list; grep(/pattern/, @array); # return filtered array @foo = grep(!/^#/, @bar); # remove lines start with # Spring, 2010 4 灵活运用 Sort 函数 • 已知 hash 表 %std = ( 学号 => 姓名， …) 要求打印该表 • 无序的打 印： print "\$_ : \$std{\$_}\n" foreach keys %std; • 按学号顺序的打 印： print "\$_ : \$std{\$_}\n" foreach sort {\$a <=> \$b} keys %std; • 按姓名顺序的打 印： print "\$_ : \$std{\$_}\n" foreach sort {\$std{\$a} cmp \$std{\$b}} keys %std; {…} 括起来的是一段代码 , 称为 BLOCK 注意 , BLOCK 和后续参数之间没有逗号！ Spring, 2010 5 Hash 表用于计数 — 单词统计 !/usr/bin/perl -w use strict; my @lines = <DATA>; # Read in data chomp @lines; # Remove CRLF my \$line = lc join " ", @lines; \$line =~ s/[^a-z]+/ /g; # remove ,:.()' my @words = split / /, \$line; my @chars = split //, \$line; print "=====List of all words:\n"; print join "\t", @words; my (\$word, \$char, \$count, %words, %chars); \$words{\$_}++ foreach @words; \$chars{\$_}++ foreach @chars; print "\n\n=====Word count:\n"; print "\$word\t\$count\n" while (\$word, \$count) = each %words; print "\n\n=====Char count:\n";...
View Full Document

{[ snackBarMessage ]}

### Page1 / 2

Lesson3 - Spring 2010 1 Perl 入门和提高 Lesson 3...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online