PERL_Templates
======================ArrayTemplates.pl============================================
#!/usr/bin/perl
print
"started
\n";
($x,
$y, $z) =
(1, 2, "hello", 4);
# assigns
$x=1, $y=2, $z="hello", 4 is discarded
print
"$x, $y, $z
\n";
# 1, 2,
hello
@pets
=
qw(Cat
Dog);
# assigns an Array
print
"@
pets\n";
# Cat Dog
@array
= (1, 2, "hello", "there");
# assigns an Array
print
"@array
\n";
# 1
2 hello there
$len
=
@array;
# $len is
now
4
print
"array_Length= $len
\n";
#
array_Length=
4
$len
=
scalar(@array);
# $len is
now
4
print
"array_Length= $len
\n";
#
array_Length=
4
$lastindex = $#array;
#
$lastindex
=
3
print
"lastindex = $lastindex \n";
# lastindex
=
3
$array[5]
= "the
end"; #
grow array
6
print
"@array
\n";
# 1 2 hello
there the end
$len
=
@array;
#
$len is
now
6
print
"array_Length= $len
\n";
#
array_Length=
6
$str2print
= join(":", ("a", "b", "c"))
;
print
"$str2print
\n";
# a:b:c
$lenn
=
length($str2print);
print
"$lenn
\n";
#5
@A1
=
split(/:/,'a:b:c');
print
"@A1
\n";
# a b c
@numbers
= (1..10);
# assigns an Array
print
"@numbers
\n";
# 1 2 3 4 5 6 7 8
9 10
@numbers_e
= (1..10)[1,3,5,7,9];
# only
works with this name
@numbers_o
= (1..10)[0,2,4,6,8,10];
# Copy without elements in []
@numbers_oo
= @numbers[0,2,4,6,8,10];
print
"@numbers_e\n";
# 2 4
6 8 10
print
"@numbers_o\n";
# 1 3 5 7
9
print
"@numbers_oo\n";
# 1 3 5 7 9
$numbers[0]++
;
#
Increment an element
print
"@numbers
\n";
# 2 2 3 4 5 6 7 8 9 10
@letters
= ("c", "l", "q", "t");
# assigns an Array
print
"@letters\n";
# c l q t
@letters
= (@letters,"z")
;
#
append an array
print
"@letters\n";
# c l q t z
push(
@letters,"z");
print
"@letters\n";
# c l q t z
?bug?
push(
@letters,"w");
print
"@letters\n";
# c l q t z w
$last =
@letters[-1];
print
"last element =
$last\n";
# last element =
w
$lastelem =
pop(@letters);
print
"$lastelem & @letters\n";
# w & c l q t z
unshift(
@letters,"a");
print
"@letters\n";
# a c l q t z
($first)
= @letters;
print
"first element = $first\n";
# first
element = a
$firstelem = shift(@letters);
print
"$firstelem &
@letters\n";
# a & c l q t z
@animals
=
("zebra","dog","lion","dolphin");
@ordered
= sort( @animals );
print
">>>@ordered
<<<\n";
# >>>dog dolphin
lion zebra <<<
@rordered = reverse( @animals );
print
">>>@rordered
<<<\n";
# >>>dolphin lion dog
zebra <<<
($anim1)
=
@animals
;
# first element
print
"$anim1\n";
# zebra
@ordered =
( )
;
# clear array
print
">>>@ordered
<<<\n";
# >>> <<<
print
"finished \n";
#
cd
/Users/donsauer/Documents/KEY/IDEA2IC/PlayWithPerl
# perl
ArrayTemplates.pl
======================StringTemplates.pl============================================
#!/usr/bin/perl
use
warnings;
print
"started
\n";
$str2print = substr("Once upon
a time", 3, 4);
print
" $str2print
\n";
# e up
$str2print2 = substr("Once upon a
time", 7);
print
" $str2print2
\n";
# on a time
$str1
=
"Once upon a time";
$str2print = uc($str1);
print
" $str2print
\n";
# ONCE UPON A TIME
$str2print
= lc($str1);
print
" $str2print
\n";
# once upon a time
$str2print = ucfirst($str1);
print
" $str2print
\n";
# Once upon a time
$str2print
= lcfirst($str1);
print
"$str2print
\n";
# once upon a time
$mystring =
"Hello, PERL!";
print
$mystring."\n";
# Hello, PERL!
substr(
$mystring, 7, 11) =
"World";
print
"$mystring\n";
# Hello, World
print
chr(65),"\n";
# A
print
ord('A'),"\n";
# 65
print
hex('0D'),"\n";
# 13
$Dec2Hex =
sprintf("%x",13);
print
"$Dec2Hex
\n";
# d
$str2print
= join(":", ("a", "b", "c"))
;
print
"$str2print
\n";
# a:b:c
@A1
=
split(/:/,'a:b:c');
print
"@A1
\n";
# a b
c
@B1
=
(a..z);
$str2print = join("",@B1)
;
print
"$str2print
\n";
# abcdefghijklmnopqrstuvwxyz
$str2print
=~ tr/a-m/A-M/;
print
"$str2print
\n";
# ABCDEFGHIJKLMnopqrstuvwxyz
$str2print
=~ tr/D-Z/d-z/;
print
"$str2print
\n";
# ABCdefghijklmnopqrstuvwxyz
$str2print =
$str2print .
"0123456789";
print
"$str2print
\n";
# ABCdefghijklmnopqrstuvwxyz0123456789
$str2print
=
$str2print .
"A"x3;
print
"$str2print
\n";
# ABCdefghijklmnopqrstuvwxyz0123456789AAA
$str2print .=
"B";
print
"$str2print
\n";
# ABCdefghijklmnopqrstuvwxyz0123456789AAAB
$result
=
rindex('perlmeme.org','m');
print
"$result
\n";
# 6
$result =
rindex('perlmeme.org','L');
print
"$result
\n";
# -1
$result
=
index('perlmem.org','mem');
print
"$result \n";
#
4
$offset
=
2;
$result =
rindex('perlmeme.org','e',$offset);
print
"$result
\n";
# 1
print
"finished \n";
print hex
'0xAf';
# 175
print
"\n";
print hex
'aF';
# 175
print
"\n";
$order_total_amt = 10.3;
$order_total= sprintf("%-20s %5.2f",
"Your total is:",$order_total_amt);
print
"$order_total
\n";
# Your total is: 10.30
$order_total= sprintf("%-30s %5.2e",
"Your total is:",$order_total_amt);
print
"$order_total
\n";
# Your total
is:
1.03e+01
$order_total= sprintf("%-1s %5.2g",
"Your total is:",$order_total_amt);
print
"$order_total
\n";
# Your total is: 10
$order_total= sprintf("%+20s %5.4d",
"Your total is:",$order_total_amt);
print
"$order_total
\n";
# Your total is: 0010
$order_total=
sprintf("%-19s %-19s %-19s",
"Your total is:",$order_total_amt,"XXX");
print
"$order_total
\n";
# Your total is:
10.3
XXX
#
cd
/Users/donsauer/Documents/KEY/IDEA2IC/PlayWithPerl
#
perl
StringTemplates.pl
====================================================================
%m.nx
m and n are optional sizes whose interpretation depends on the type of
field, and x is one of:
c
Character
ld
Long decimal number
u
Unsigned decimal number
lu
Long unsigned decimal
number
lx
Long hexadecimal number
o
Octal number
lo
Long octal number
====================================================================
Special Chars
'text'
-» literal text except \' and \\
"text"
-» special chars executed
q/text/
-» use / for '
qq/text/
-» use / for "
\n
-» newline
\r
-» return
\t
-» tab
\f
-» formfeed
\007
-» octal
\xff
-» hex
\cC
-» control C
\"
-» "
\\
-» \
\l
-» lowercase next
\u
-» uppercase next
\L
-» lowercase all
\U
-» uppercase all
\E
-» end all
+ * ? . ^ $ @ % ( ) [ ] { } | \
As number:
As string:
=======================MATCH_REPLACE=================================
$dataVariable
=~
/template/ ;
$dataVariable
represents piece of data are matching against;
=~
true if str matches pat
!~
true if str not matches
/
are used to enclose the
regular expression syntax.
$dataVariable =~ /.+\@.+/ ;
.+
means "any character one or more times".
\@
@ symbol needs to be escaped with a backslash (\) to
ensure does not
misinterpret
to match a slash you would have to use \/
$dataVariable =~ /^\w+\@\w+(\.org|\.net)$/i ;
^
represents start of data {an anchor symbol}
because
it matches a boundary
$
anchor symbol represents end of the data.
\w
symbol includes all characters from a-z and
AZ and
0-9
i
ignore case match case-insensitively.
x
ignore whitespace
if
($dataVariable =~ /^\w+\@\w+(\.org|\.net)$/i ){ ...statements if
true... }
($string
=~ /pattern/) ##
true if the pattern is found somewhere in the string
("binky"
=~ /ink/) ==> TRUE
("binky" =~ /onk/) ==> FALSE
next if
m/^\s*$/;
# will
skip blank lines.
$pet
=~ s/\bcat\b/feline/ig ;//search-end-replace any "cat" with
"feline".
s/
performing a substitution
\b
surround "cat"obliging
Perl to find a space or other symbol around it
g
Without the g modifier, substitution would only replace first
occurrence of "cat"
$search =~ s/[^\w|
]/,/g
; //"black cat,dog*mouse/frog" => "black
cat,dog,mouse,frog"
^\w
not containing a word class character or a space
[^\w|
]
square brackets) tells Perl to exclude AZ, AZ, 0-9 characters
listed inside class.
$userinput
=~
s/\n//g ;
# replaces newline
(\n) with null;
$string
=~ s/<([^>]|\n)*>//g ;
# Strip HTML tags
from a string
$string
=~ s/^\s+//
;
#
Strip leading spaces from a string
$string
=~ s/\s*$//
;
# will
trim trailing spaces
$string
=~ s/(\w)/$1:/g
;
# "ab" -> "a:b:"
$`
add before match
$'
add after match
$&
matched
[^pat]
chars not in pattern
.
Match any character
[abc]
Match a or b or c
\w
Match "word" character
(alphanumeric plus "_")
[a-z]
Match any char from a thru z
\W
Match non-word
character
\s
Match whitespace
character
\S
Match non-whitespace
character
\d
Match digit character
\D
Match non-digit
character
\t
Match tab
\n
Match newline
\r
Match return
\f
Match
formfeed
\a
Match alarm (bell,
beep, etc)
\e
Match escape
\021
Match octal char
( in this case 21 octal)
\xf0
Match hex
char ( in this case f0 hexidecimal)
*
Match 0 or
more times
+
Match 1 or
more times
?
Match 1 or
0 times
{n}
Match
exactly n times
{n,}
Match at
least n times
{n,m}
Match at least n
but not more than m times
?
match 0 or
1 occurrences of the pattern to
its left
*
match
0 or more occurrences of
the pattern to its left
+
match 1 or more occurrences of the pattern
to its left
|
match-- (vertical bar) logical or --
matches the pattern either on its left or right
( )
match parenthesis -- group sequences of patterns
^
matches the start
of the string
$
matches the end
of the string
abc
matches a or b or c
a-z
matches any char from a thru z
^pat
matches chars not in pattern
c*
matches zero or more c's
c*?
matches lazy * (as few as possible)
c+
matches one or more c's
c+?
matches lazy +
c?
matches zero or one c
c??
matches lazy ?
c{3,7}
matches between 3 and 7 c's
c{3,}
matches 3 or more c's
c{3}
matches exactly 3 c's
c{3,7}?
lazy
=======================MATH===========================================
$a
=
9 ** 10;
# Nine to the power of
10
$a =
5
%
2;
# Remainder of 5 divided by 2
++$a;
#
Increment $a and then return it
$a++;
#
Return $a and then
increment it
--$a;
#
Decrement $a and then
return it
$a--;
# Return $a and then decrement it
$a
=
$b .
$c;
# Concatenate $b and $c
$a
=
$b x $c;
# $b
repeated $c
times
$a =
$b;
#
Assign
$b to $a
$a +=
$b;
# Add $b to $a
$a -=
$b;
#
Subtract $b from $a
$a .=
$b;
#
Append $b onto $a
==
equality
!=
inequality
<
less than
>
greater than
<=
less than or equal
>=
greater than or equal
eq
equality
String comparison
ne
inequality
lt
less than
gt
greater than
le
less than or equal
ge
greater than or equal
&&
and Boolean
logic
||
or
!
not
for
($i=0; $i < $N_proc;
$i++)
{ print
"*$processValue[$i]*\n"; }
=======================PADDING============================
print
"Now ", time(),
" seconds since 1970.\n"; # The time is now 1191812029 seconds since
1970.
$text
=
"Left pad a string";
$pad_len
= 30;
$padded =
sprintf("%${pad_len}s \n", $text);
print
$padded
;
#
Left pad a string
$num = 33;
$padded =
sprintf("%0${pad_len}d",
$num);
print
$padded
,"\n";
# 000000000000000000000000000033
$text
=
"Right pad a string";
$padded = sprintf("%-${pad_len}s", $text);
print
$padded
,"####\n";
# Right pad a
string
####
$text
=
"Right pack and tunct to 30 a string";
$padded = pack("A$pad_len",$text);
print
$padded
,"####\n";
# Right pack and tunct to 30 a s####
$text
=
"Right pad a string";
$pad_char = "#";
$padded = $pad_char x ( $pad_len - length(
$text ) ) . $text ;
$text
=
"Right pad a string2";
print
$padded
,"\n";
# ############Right
pad a string
$pad_len
= 30;
$pad_char =
"@";
substr(
$text,0,0) = $pad_lenx($pad_len -length($text)
);
$text .= $pad_char x ( $pad_len - length(
$text ) );
print
$text
,"#\n";
# @@@@@@@@@@@@Right
pad a string#
$line =
"MakeUpperCase";
$line = uc($line);
print
$line
,"\n";
# MAKEUPPERCASE
$line
=
"make first letter UpperCase";
$line =~
s/(\w+)/\u\L$1/g;
print
$line
,"\n";
# Make First Letter Uppercase
$string
=
" Strip Leading edges";
$string =~
s/^\s+//;
$string =~
s/\s+$//;
print
$string
,"\n";
# Strip Leading edges
# cd /Users/donsauer/Documents/IDEA2IC/PlayWithPerl
# perl paddingStrings.pl
============================================================================
$line =
<STDIN>;
## read one line from the STDIN file handle
chomp(
$line);
## remove the trailing "\n" if present
$line2 = <FILE2>;
## read one line from the FILE2 file handle
while
($line =
<STDIN>)
## read every line of a file
{ ## do something with $line
}
open(
F1,
"filename");
## open "filename" for reading as file handle F1
open(
F2,
">filename");
## open "filename" for writing as file handle F2
open(
F3, ">>appendtome") ## open
"appendtome" for appending
close( F1);
## close a file handle
open(
F4, "ls -l
|");
## open a pipe to read from an ls process
open
(F5, "| mail $addr"); ## open a pipe to
write to a mail process
open(
FILE, $fname)|| die "ouch\n";
@a =
<FILE>;
## read the whole file in as an array of lines
=================================================================
$dict{"bart"} = "I didn't do
it";
## %dict contains key/value pairs (("bart" => "I didn't
do it"),
$dict{"homer"} = "D'Oh";
$dict{"lisa"} =
"";
## %dict contains
key/value pairs("homer" => "D'oh"), ("lisa" => ""))
$string = $dict{"bart"};
## Lookup the key "bart"
to get ## the value "I didn't do it"
$string =
$dict{"marge"}; ##
Returns undef -- there is no entry for "marge"
$dict{"homer"} = "Mmmm, scalars";
##
change the value for the key ## "homer" to "Mmmm, scalars"
@array =
%dict;
## @array = ("homer","D'oh","lisa","","bart","I didn't do it");
##
## (keys %dict) looks like ("homer", "lisa, "bart")
## or use (sort (keys %dict))
%dict
= (
"bart" => "I didn't do it",
"homer" => "D'Oh",
"lisa" =>
"",); #can use => instead of comma
=================================================================
while (expr) {
stmt;
stmt;
}
for (init_expr; test_expr; increment_expr) {
stmt;
stmt;
}
## typical for loop to count 0..99
for ($i=0; $i<100; $i++) {
stmt;
stmt;
}
foreach $var (@array) {
stmt; ## use $var in here
stmt;
}
You can also use the PERL
arithmetic functions:
atan2(EXPR) - arctangent of X/Y in the range pi to - pi
cos(EXPR) - cosine
hex(EXPR) - decimal value of EXPR interpreted as hex string
index(STR,SUBSTR,POSITION) returns the position of the first occurrence
of SUBSTR in STR. The POSITION, if specified, says where to start
looking. Positions are based at 0. If SUBSTR is not found, -1 is
returned.
int(EXPR) - the integer portion of EXPR
length(EXPR) - length in characters of the value of EXPR
log(EXPR) - logarithm of EXPR
oct(EXPR) - the decimal value of EXPR interpreted as an octal string
ord(EXPR) - the numeric ASCII value of the first character of EXPR
rindex(STR,SUBSTR,POSITION) - just like index except returns the
position of the last occurrence of SUBSTR in STR
sin(EXPR) - "Sorry, there's nothing wicked about this function. It
merely returns the sine of EXPR."
sqrt(EXPR) - square root of expression
Examples:
$order_subtotal=$item1_amt + $item2_amt + $item3_amt + $item4_amt;
$order_tax=int($order_subtotal*8.25)/100;
use strict;
use warnings;
sprintf(FORMAT,LIST)
- returns a string formatted by the usual printf conventions.
The FORMAT string contains text with embedded field specifiers into
which the elements of list are substituted, one per field. Field
specifiers are roughly of the form:
=================================================================
. Match any character
\w Match "word" character (alphanumeric plus "_")
\W Match non-word character
\s Match whitespace character
\S &nb