Very Basic Perl Tricks

Download Report

Transcript Very Basic Perl Tricks

Very Basic Perl Tricks








A Few Ground Rules
File I/O and Formatting
Operators, Flow Control Statements
Regular Expression
Subroutines
Hash (Associative Arrays)
Built-in Functions
Miscellaneous
Steven Leung
Very Basic Perl Tricks
1/12
A Few Ground Rules


All scalar variables start with $
Regular array as a whole: @name



Hash (associative array) as a whole: %name





Element of @name is $name[index], where index is a numeric value,
default starting index is 0, define-able thru $].
$#name returns the last index of the array name ($] -1 if undefined)
Element of %name is $name{key}, where key is a string value
The keys operator returns a regular array containing all the keys
All variables are global variables, unless declared explicitly with
the local operator
Scalar, array, hash, file handle, and subroutine names have
separate name spaces
The default operand of pattern matching, IO operations, and
most (but not all) of the built-in functions is $_
Steven Leung
Very Basic Perl Tricks
2/12
A Few Ground Rules (cont.)

It is legal to reference a variable before it gets a value assigned.
When evaluated, a variable without a value assigned has the
value of “undefined”, which will evaluate to false logically.


Variables in “…” (‘…’) will (not) be substituted with its value



Use the defined operator to distinguish 0(or “”) and “undefined”
Same as shell interpretation
Functions can be chained together, and the evaluation (following
the LISP convention) started from the right and the results feed
back to the left function
An evaluation can produce results of different types. The exact
type returned depends on the context, i.e., the data type
expected by the assignment or function argument
Steven Leung
Very Basic Perl Tricks
3/12
File I/O


Predefined file handler: STDIN, STDOUT, STDERR
open(F, “my_file”) # Open my_file for read
while (<F>) { ... }
# Read a line thru F to $_


open(O, “>my_ofile”) # Open my_ofile for write
print O “this,”, “that,”, “whatever\n”;





<> is the readline operator
No comma between O (the file handler) and the rest
If O is omitted, the default is STDOUT
printf and sprintf accept a string to specify format, same as in C
E.g. printf O (“%s %d”, $string, $num);
Pipes can be added to the filename part:

open(F, “pwd|”);
Steven Leung
Very Basic Perl Tricks
4/12
Output Formatting

# default name is STDOUT
format name =
@<<<<<< @||||| @>>>>>> @###.##
$var1, $var2, $var3, $var4
.
left, center, right justified
fixed-point number
Format statement must be ended with a ‘.’ at the 1st col. of a new line.

Format is “executed” by the write command
foreach (@some_array) {
# set up $var1, $var2, $var3, $var4
write;
}

Use select(File_Handler); $~ = Format_Name; to switch format
Steven Leung
Very Basic Perl Tricks
5/12
Operators, Flow Control Stmts

C-Like Operators: ++, ||, &&, +=, …





If (expr) { … }
[ [elsif (expr) { … }]
else { … } ]
while (expr) { … }


foreach (<>) { ... }
# Read in the whole file first
for (expr; expr; expr) { … }


while (<>) { ... } # Same as while ($_=<STDIN>) { ... }
foreach [$var] (@array) { … }


For numeric: ==, !=, <, >, <=, >=, <=>
For strings: eq, ne, lt, gt, le, ge, cmp, =~ (see Reg. Expr.)
File test:
-e, -f, -d, ...
for ($i=1; $i<=10; $i++) { ... }
last, next

while (<>) { next if /^#/; ... last if /^END/ }
Steven Leung
Very Basic Perl Tricks
6/12
Regular Expression

Characters that have special meanings in /pattern/:
() [ ] . - + * ? ^ $ \ | /

Short-hand notation of often-used regular expressions:




\D  Not \d
\S  Not \s
\W  Not \w
Pattern matching operator =~




\d  digit
\s  white space
\w  alphanumeric + _
[expr =~] [m]/Pattern/[i]
# Just check if pattern found
[$var =~] s/Pattern/Replace/[g][i][e] # Substitution
[$var =~] tr/Search_list/Repl_list/
# Translate
Examples



$str =~ /^\s*module\s+(\w+)/;
($cell, $inst) = $str =~ /^\s*(\w+)\s+(\S+)/;
($cell, $inst) = $str =~ /^\s*(\w+)\s+([^\s,\(]+)/;
Steven Leung
Very Basic Perl Tricks
7/12
Subroutines

Defining a subroutine
sub my_func {
local($a, $b, $c) = @_;
# Code to process $a $b $c
return($some_val);
# return(@val_array);
}

Calling the subroutine my_func
$ret_val = &my_func($x, $y, $z);
 Note that arguments ($x, $y, $z) are passed to the subroutine
through the array @_

Anonymous subroutine examples

foreach $n (sort {$a cmp $b} @names) { . . . }

$a and $b are values passed to the anonymous sub by sort func
foreach (sort {$dly{$b}<=>$dly{$a}} keys %dly) { ... }
cmp/<=> compares by alphabetical/numeric order
Steven Leung
Very Basic Perl Tricks
8/12
Hash (Associative Array)

Think about hash as a 2-column table
Name of the hash (table)
%area_of
key
value
INVX1
17.0
AND2X1
25.5
SDFFX1
153.0
Keys are of string type

Values are of scalar type (numeric/string)
The values are accessed by $name{key}

Example: $area_of{$cell_type}

Function keys returns a regular array (list) of all keys

Common use of hash table as a flag on an array of obj.

Example: if (!$seen{$cell_type}++) { ... }
Steven Leung
Very Basic Perl Tricks
9/12
Build-In Functions (Most Used)
# Chop off the last char from $str

chop [$str]

split[(/pat/,$str)]
 split $str into an array with /pat/ as field separator

push(@array,LIST)

shift[(@array)]

grep(EXPR, LIST)
 Return an array of elements from LIST for which EXPR is true
 Ex. @cells_used = grep(!$seen{$_}++, values %cell_of);

warn LIST

die LIST


# append the LIST to @array
# shift the 1st element out
# print LIST to STDERR
# print LIST to STDERR, then exit
open(F, infile) || die “*** Can’t open infile\n”;
exec/system(LIST)
Steven Leung
# non-/blocking system call
Very Basic Perl Tricks
10/12
Miscellaneous

1st line: #!/usr/local/bin/perl
Command line args are set to built-in array @ARGV

Useful command line switches



-[p|n]e ‘perl statements’

Both p,n wrap the statements with while (<>) { ... }
-p also print $_ after the statements
-i : in-place editing
Use qq/q to change double/single quote character


print qq|Pcap = $pincap_of{“$cell_of{$inst}:$pin”}\n|;
Other useful special variables




$0: Name of the perl script file from the command line
$`, $&, $’ : preceding, matching, and following strings
Pattern matching of /\([^\)]+\)/ on line: abc ( 123, 321 ) xyz
$` = “abc “, $& = “( 123, 321 )”, $’ = “ xyz”
Steven Leung
Very Basic Perl Tricks
11/12
Exercise
Write the get_cell_stat script for the following input/output
% get_cell_stat bloom.def > bloom.cell_stat
bloom.def
Version 5.2 ;
...
get_cell_stat
DESIGN bloom ;
...
COMPONENTS 76759 ;
- bloom_top|cmem|..|U204 ANDX1 ;
- bloom_top|regs|..|U31 XOR2X2 ;
...
bloom.cell_stat
END COMPONENTS
Cell
Count
Perc
...
Acc
------------------------------NANDX1
9104 11.86 11.86
INVX1
8324 10.84 22.71
...
Steven Leung
Very Basic Perl Tricks
12/12