130 likes | 266 Vues
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. A Few Ground Rules. All scalar variables start with $ Regular array as a whole: @ name
E N D
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 Very Basic Perl Tricks
A Few Ground Rules • All scalar variables start with $ • Regular 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) • Hash (associative array) as a whole: %name • 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 $_ Very Basic Perl Tricks
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. • Use the defined operator to distinguish 0(or “”) and “undefined” • Variables in “…” (‘…’) will (not) be substituted with its value • 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 Very Basic Perl Tricks
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 $_ • <> is the readline operator • open(O, “>my_ofile”) # Open my_ofile for write print O “this,”, “that,”, “whatever\n”; • 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|”); Very Basic Perl Tricks
Output Formatting left, center, right justified fixed-point number Format statement must be ended witha ‘.’ at the 1st col. of a new line. # default name isSTDOUT • formatname = @<<<<<< @||||| @>>>>>> @###.## $var1, $var2, $var3, $var4 . • 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 Very Basic Perl Tricks
Operators, Flow Control Stmts • C-Like Operators: ++, ||, &&, +=, … • For numeric: ==, !=, <, >, <=, >=, <=> • For strings: eq, ne, lt, gt, le, ge, cmp, =~ (see Reg. Expr.) • File test: -e, -f, -d, ... • If (expr) { … } [ [elsif (expr) { … }] else { … } ] • while (expr) { … } • while (<>) { ... } # Same aswhile ($_=<STDIN>) { ... } • foreach [$var] (@array) { … } • foreach (<>) { ... } # Read in the whole file first • for (expr; expr; expr) { … } • for ($i=1; $i<=10; $i++) { ... } • last, next • while (<>) { nextif /^#/; ... lastif /^END/ } Very Basic Perl Tricks
Regular Expression • Characters that have special meanings in /pattern/: () [ ] . - + * ? ^ $ \ | / • Short-hand notation of often-used regular expressions: • \d digit \D Not \d • \s white space \S Not \s • \w alphanumeric + _ \W Not \w • Pattern matching operator =~ • [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,\(]+)/; Very Basic Perl Tricks
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 Very Basic Perl Tricks
Hash (Associative Array) Name of the hash (table) Keys are of string type Values are of scalar type (numeric/string) %area_of • Think about hash as a 2-column table • 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}++) { ... } Very Basic Perl Tricks
Build-In Functions (Most Used) • chop [$str] # Chop off the last char from $str • split[(/pat/,$str)] • split $str into an array with /pat/ as field separator • push(@array,LIST) # append the LIST to @array • shift[(@array)] # shift the 1st element out • 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 # print LIST to STDERR • die LIST# print LIST to STDERR, then exit • open(F, infile) || die “*** Can’t open infile\n”; • exec/system(LIST)# non-/blocking system call Very Basic Perl Tricks
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’ Bothp,nwrap the statements with while (<>) { ... } -palso print $_ after the statements • -i : in-place editing • Use qq/q to change double/single quote character • printqq|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” Very Basic Perl Tricks
Exercise bloom.def get_cell_stat • Version 5.2 ; • ... • DESIGN bloom ; • ... • COMPONENTS 76759 ; • bloom_top|cmem|..|U204 ANDX1 ; • bloom_top|regs|..|U31 XOR2X2 ; • ... • END COMPONENTS • ... bloom.cell_stat Cell Count Perc Acc ------------------------------- NANDX1 9104 11.86 11.86 INVX1 8324 10.84 22.71 ... Write the get_cell_stat script for the following input/output % get_cell_stat bloom.def > bloom.cell_stat Very Basic Perl Tricks