Expand All Collapse All
- 1. Getting Started
- 1. Before we start
- 1. What's Perl
-
Perl is a programming language.
It stands for Practical Extraction and Reporting Langauge.
It's the best language to manipulate text, e.g. html.
- 2. Why this guide
-
This guide is my Perl how-to list.
It's easier to find the solutions here than in a book.
This guide is to the point, the books usually are not.
This guide is free and weighs nothing.
This guide is always available.
This guide will only get better with time for i update it.
- 3. Guide writing conventions
-
Bold text is program code.
Italic text is program output.
For searching this entire guide by words:
-click the "Expand All" button, (see above)
-then click Ctrl-f on your keyboard.
- 4. Credits
- 1. What's Perl
- 2. Getting it running
- 1. Get Perl
-
If you're on Linux then Perl is most likely already installed, skip to next section.
But if you're on windows then go here and get
"Windows (x86)" package, MSI version.
Save it on your computer and run it.
Now you have perl.
- 2. Making the most elementary script
-
Open a text editor and copy the following into it:
#!/usr/bin/perl
print STDOUT "Hello World\n";
<> #keeps the console window open after program finishes.
#Save the file.
#Now you have a runnable perl script saved on your computer.
- 3. Run perl scripts
-
Go to cmd (Start->run, and there type "cmd").
Now go to where you saved your per script and type:
%perl scriptname.pl
to have perl search for the script in all @INC directories:
%perl -S scriptname.pl
to only check the syntax of the script:
%perl -c scriptname.pl
to write perl scripts directly in cmd:
%perl -e 'print "@INC";'
- 1. Get Perl
- 3. Visual debugger
- 1. Install
-
in cmd:
ppm
install devel-ptkdb
exit
Then you're done.
The computer must be connected to the internet.
on linux:
enter the console,
sudo apt-get install libdevel-ptkdb-perl
youre done.
- 2. Help
-
To get help about the Visual Debugger module is the same as getting
help for any other module.
in cmd:
perldoc Devel::ptkdb
- 3. Run
-
in cmd:
perl -d:ptkdb scriptname.pl
- 4. Make debugger default
-
in cmd:
set PERL5DB='BEGIN {require "Devel/ptkdb.pm";}
- 5. Specifics
-
Ctrl-r (resets)
Ctrl-q (quits)
Ctrl-h (help)
L = Ten lines after current line.
C = Stop stepping through the program.
H = Gets you help while the debugger is running.
|h = Pauses between pages.
H and then type a function, shows you help about that function.
T = Toggles between trace modes in the script.
L = List the next ten lines of code.
C = To continue executing past a breakpoint.
L = Print all the breakpoints.
D = Deletes breakpoints.
- 1. Install
- 4. The greatest text editors
-
After much working of checking out miscellaneous text
editors the following have turned out to be the best:
Editor Operating System Vim Linux Kate Linux Kubuntu Crimson Windows RJ TextEdit Windows
- 5. Get help
- 1. Get information about Perl functions
-
perldoc -t -f function-name.
#t = Format text.
#f = Function.
#Example:
perldoc -f print
- 2. Good Perl forums
- 1. Get information about Perl functions
- 1. Before we start
- 2. Variables
- 1. Instantiate
- 1. About
-
You can instantiate "$name", and then "my $name".
Those will be two different variables.
- 2. Global
-
$name = "Hermann";
#$name is now instantiated as a global variable.
#Global vars run until the end of the script.
#As scripts get larger, using global vars becomes more inviting
to debugging problems for you start loosing track of all of those names.
- 3. My
-
my $name = "Hermann";
#$name is now instantiated as a my variable.
#The benefits of using my:
#-Take less memory.
#-Take less cpu.
#-Theyre empties after the brackets they are within run out.
# That means they dont interfere with code outside.
# Thats very important, especially when the program gets big.
#Use my often.
- 4. Local
-
local $name = "Hermann";
#$name is now instantiated as a local variable.
local saves a copy of an existing one.
local = goes down.
#Local vars are rarely used, their working is obscure to me.
- 5. Our
-
our makes variables global within a file.
#our makes variables available also in all pacakges down.
our $val = 3;
#thats not the case with plain global...
$var = 3;
- 6. Default
-
$x ||= "The man";
#$x will now become "The man", unless its already defined.
#im having difficulties getting this to work though.
- 7. Constants
-
constant $pi = 3.14;
#$pi is now a constant var, meaning the content can never be changed.
- 1. About
- 2. Math
- 1. Basic (+ - * /)
-
$age = 27;
$age = ($age + 2);
#$age is now 29.
#The others go without saying.
- 2. Exponent
- 1. Normal (**)
-
$men_no = 4;
$men_no = $men_no**2;
#$men_no is now 16. - 2. Square Root
-
$value = sqrt(16);
#$value is now: 4.
#Square root is the same as: $value**0.5
- 1. Normal (**)
- 3. Modulus (%)
-
$remaining_pie = (17 % 5);
#$remaining_pie is now 2 because 17 - 5 - 5 - 5 is two.
#The modulus continues to subtract until the next subtraction will bypass zero.
#Whats left then is the outcome.
- 4. Random
- 1. Basic
-
$random = rand(101);
#$random will now be a random value between 0 and 100.
- 2. Truly random
-
user Math::TrulyRandom;
$random = truly_random_value();
#Its slow but the outcome is truly random.
#Its time consuming.
- 3. Yet another
-
use Math::Random;
$random = random_uniform();
#Math::Random also includes a wide variety of related functions.
- 1. Basic
- 5. Approximate
-
$average = 3.33333333;
$average = sprintf("%.2f", $average);
#Now $average has only two extra digits after the point.
- 6. Absolute
-
$value_original = -5;
$value_absolute = abs($value_original);
#$value_absolute is now 5.
- 7. Int
-
#Forces the outcome to turn itself into an integer.
#Example:
$people_quantity = 10;
$people_quantity = $people_quantity / 3;
#people_quantity is now 3.33333...
int $people_quantity;
#$people_quantity is now 3.
- 8. Logarithm
-
$log_e = log(5); #$log_e is now the log of 5.
use POSIX qw(log10);
$log_10 = log10(VALUE);
- 9. Imaginary
-
use Math::Complex;
$a = Math::Complex->new(3,5); #3 + 5i
$b = Math::Complex->new(2,-2);#2 - 2i
$c = ($a * $b);
#$c is now 16 + 4i.
- 10. Prevent precision loss with big numbers
-
use Math::BigInt;
$bi = Math::BigInt->new('11111');
on how to use these numbers see documentation about the bigint module.
- 1. Basic (+ - * /)
- 3. String
- 1. Add
-
$surname = "Hermann";
$lastname = "Ingjaldsson";
$full_name = "$surname "."$lastname";
#$full_name is now "Hermann Ingjaldsson.
$surname .= " is here.";
#$surname is now "Hermann here.";
- 2. Split
- 1. On point
-
my $price = 6.14;
($dollars, $cents) = split('.', $price);
#$dollars is now: 6.
#$cents is now 14.
- 2. Every element
-
$text = "Hermann was here";
@splitted = split(//, $text);
#@splitted is now = (H, e, r, m, a, n, n, , ,w, a, s, , ,h, e, r, e)
- 1. On point
- 3. Case Changing
-
$name = "HERMANN";
lc($name); #$name is now: hermann.
ucfirst($name);#$name is now: Hermann.
uc($name); #$name is now: HERMANN.
- 4. Index and Rindex
-
$_ = "Its a Perl Perl Perl Perl World.";
$left = index $_, 'Perl';
#$left is now 7.
$right = rindex $_, 'Perl';
#$right is now some number higher than 7.
- 5. Substring
-
my $str = "Its a Perl World";
print substr($str, 7, 4), "\n";
#Prints "Perl"
print substr($str, 7), "\n";
#Prints "Perl World"
- 6. Length
-
$name = "Arnaldur";
$name_length = length($name);
#$name_length is now: 8.
- 7. Reverse
-
$name = "Hermann";
$name_reverse = reverse($name);
#$name_reverse is now: "nnamreH".
- 8. Testing for stringness
-
if ($x & ~$x){print STDOUT "Its a string.\n";}
- 9. Pack
-
$string = pack("ccc", 88, 89, 90);
print join(", ", unpack "ccc", $string);
- 10. Pick out of string by pattern
-
my %cvars_website = map { /$tpickup_pattern/gi } $url_content;
- 1. Add
- 4. Specials
- 1. Shortcutting
-
$age = 3;
$age += 4;
#Is the same as: $age = $age + 4;
$age **= 2;
#Is the same as $age = $age**2;
#This kind of shortcutting can be done with all the operators.
- 2. Auto-Increment
-
$age = 27;
$age++;
#$age is now 28.
- 3. Swapping
-
($x, $y) = ($y, $x);
#The variables have now swapped values.
- 4. Storing Large Variables
-
use Storable qw(nstore, retrieve);
my $status = nstore \%hash, "file.dat";
- 5. Execute variable as code
-
$code = sub {"print "Hello\n";";}
&{$code};
%hello
- 1. Shortcutting
- 5. Comparison
- 1. Numeric
-
#== means equals
#!= means not equals
#< means lesser than
#> means greater than
#<= means lesser than or equal
#>= means greater than or equal
#Example:
$age = 25;
if ($age < 30) {print STDOUT "Hes too young.\n";}
else {print "Hes old enough.\n";}
- 2. String
-
#eq means equals
#ne means not equals
#lt means lesser than
#gt means greater than
#le means less than or equal
#ge means greater than or equals
$man_one = "Hermann";
$man_two = "Hermann";
if ($man_one eq $man_two) {print STDOUT "Its the same man!\n";}
- 3. Logical
-
#"and" means and.
#"or" means or.
#"not" means not.
#"xor" means or, but if both are true then return false.
#Example:
$name1 = "Hermann";
$name2 = "Margret";
#if name1 contains h, and name2 contains m, then print "They both fit their criteria.\n".
if ($name1 =~ h and $name2 =~ m) {print "They both fit their criteria.\n";}
- 4. Defined
- 1. if Defined
-
If (defined $var){do_something};
- 2. Make undef
-
undef $var;
- 1. if Defined
- 5. Exists
- 1. If exists
-
If (exists $var){do_something.}
- 1. If exists
- 6. Contains
-
my $name = "Hermann";
if ($name =~ /her/) {print "It matches the criteria.\n";}
#if $name contains "her", then print "It matches the criteria.\n".
#=~ should be read as contains.
#Contains is the basis for all Text Manipulation. (see Text Manipulation)
- 1. Numeric
- 6. Conversion
- 1. ASCI
-
$ASCI_for_a = chr("a");
#chr means: to ASCI.
- 2. UniCode
-
$unicode_for_a = ord(a);
#ord means: to unicode.
- 3. Binary
-
$num = bin2dec('0110110'); #$num is now 54.
$binstr = dec2bin(54); #$binstr is now 0110110.
- 4. Oct
-
$number = oct($octal);
- 5. Hex
-
#hex<=>number conversion
my $The_Number = 97;
$hex = unpack("H*", pack("N", $The_Number));
print $hex;
print "\n";
print hex($hex); # back to original
- 6. Roman
-
use Roman;
$roman = roman(57); #$roman is now lvii.
$roman = Roman(57); #$roman is now LVII.
if isroman($roman){$arabic = arabic(lvii);} #$arabic is now 57.
- 1. ASCI
- 7. Most Common Errors
- 1. Confusing == with eq
-
#Using "==" when you should use "eq", and vice versa.
== is for numbers, eq is for strings.
- 2. Confusing == with =
-
#Using the assignment operator "=" when you really meant the conditional operator "=="
- 3. "$var" And '$var'
-
#"" interpret their vars.
my $age = 27;
print STDOUT "Hermann is $age years old."; #Will print: Hermann is 27 years old.
print STDOUT 'Hermann is $age years old.'; #Will print: Hermann is $age years old.;
- 4. Sometimes when you divide, e.g. 1,256 will be treated like 1
-
#In order to prevent that you must first do.
$number = "$number";
- 5. Accessing Variables Within Sub-Function Without Adding To That Module Declaration
-
my $former = shift;
my $latter = shift;
our @EXPORT = (@EXPORT, "@$former", "@$latter");
- 1. Confusing == with eq
- 8. Predefined
-
$, = ";";
print 1,2,3;
%1;2;3
$. = current line.
$/ = newline by default. It's what perl expects to be at newlines.
$^0 = operating system name.
$| disables buffering.
without it scripot output will go immediately to the server.
some servers give problem if it's not undef.
$. = current input line number.
$/ = input record separator.
$^0 = osversion
$^S = inside eval or not.
$| = disable buffering.
means script output will appear on the web immediately.
some web servers produce problems unless it's 1.
- 9. English module
- 1. Instantiate
- 3. Arrays
- 1. Add
- 1. Part
-
@names_there = qw(hemmi, siggi, kalli, joi);
@names_here = @names_there[0 .. 2];
#@names_here now contains (hemmi, siggi, kalli).
- 2. Array
-
@both = (@former, @latter);
- 3. Element
- 1. At beginning
-
unshift (@array, $var);
- 2. Within
-
$names[4] = "Hermann";
#Array element no.5 in @names has now become "Hermann".
#Whatever was there before has now been deleted.
- 3. At end
-
push (@array, $var_to_add);
#or
@names = (@names, "Hermann", "Siggi");
#Here "Hermann" and "Siggi" have been added to @names.
#push is more efficient than normal array addition.
- 4. Beyond end
-
@companies = ();
$companies[2] = "DCGN";
#@companies is now: (undef, undef, "DCGN").
- 1. At beginning
- 5. Within
-
my @names = qw(hemmi, siggi, kalli, joi);
my @names_labeled = join('+', @names);
#@names_labeled is now: (+hemmi, +siggi, +kalli, +joi).
- 1. Part
- 2. Get
- 1. Size of array
-
$name_quant = ($#names + 1);
- 2. Last element
-
@ages = qw(12, 16, 22);
$last_element = $ages[$#ages];
#$last_element now contains the value 22.
- 3. What fulfills criteria
-
@original = qw(2, 15, hemmi, jonathan);
@with_criteria = grep { /\d/ } @original;
#@with_criteria now contains: (2,15).
#For more on criteria making see 11.Text Manipulation.
@div5 = grep {not $_ % 5} @original;
#@div5 now contains.. something.
- 4. Whats in either/both
-
#Union = either.
#Intersection = both.
my @either = @both = @diff = ();
my %either = %both = %count = ();
foreach $e (@former, @latter) { $either{$e}++ && $both{$e}++; }
@either = keys %either;
@both = keys %both;
#There should be a "@in_both = in_both(\@former, \@latter);"
#And a "@in_either = in_either(\@former, \@latter);" function
- 5. Whats in former not latter
-
@former = qw(1, 2, 4);
@latter = qw(2,16, 18);
my %seen @former_only;
@seen{@latter} = ();
foreach $item (@former)
{push (@former_only, $item) unless exists $seen{$item};}
undef $item;
#@former_only now contains: (1, 4).
- 1. Size of array
- 3. Instantiate
- 1. Manually
-
#Instantiate a global array. (exists to the end of the script)
@names = qw(Hemmi, Siggi, Jonathan);
#Instantiate a temp array. (exists to the end of the current block{}.
my @names = qw(Hemmi, Siggi, Jonathan);
- 2. Automatically
-
#@numbers becomes: (1, 2, 3, etc 100)
@numbers = (1 .. 100);
#@alphabet becomes: (a, b, c, ... z)
@alphabet = (a .. z);
- 3. An Array Whos Name Is, "The Content Of A Variable."
-
$array_name = "TheMan";
@$array_name = ("is Hermann");
print STDOUT @TheMan;
#Prints: "is Hermann".
- 4. Fill x Elements Of Array With One Value
-
@one = (0) x 100;
#Puts (0) into the first 100 elements of the array.
- 1. Manually
- 4. Remove repetitions
-
@ages = qw(15, 15, 15, 17, 22, 28);
@ages_without_repetitions = grep { ! $seen{$_} ++ } @ages;
#@ages_without_repetitions now contains: (15, 17, 22, 28).
- 5. Operate on each element
-
@sizes_of_files = map { -s $_ } @files;
@squares_of_ages = map { $_**2 } @ages;
#or: foreach (@prices){$sum += $_;}
#$sum now contains the sum of all the elements in the array.
@original = qw(2, 15, hemmi, jonathan);
@with_criteria = grep { /\d/ } @original;
#@with_criteria now contains: (2,15).
#For more on criteria making see 11.Text Manipulation.
@div5 = grep {not $_ % 5} @original;
#@div5 now contains.. something.
- 6. Get elements fitting a pattern
-
my @links_and_descs_withdom = grep /$contains_domain/, @links_and_descs;
- 7. Print
- 1. Array
-
@names = qw(hemmi, siggi, jonathan);
for(@names) {print STDOUT;}
#prints the entire array to computer screen.
- 2. Array With Comma Between Elements
-
print STDOUT join (", ", @temp);
- 3. Array With Every Element In Second Power
-
foreach (@temp){print STDOUT "$_: ", $_ * $_, "\n";}
- 1. Array
- 8. Remove
- 1. Elements
- 1. At beginning
-
$var = shift (@array);
- 2. Within
-
@names = qw(hemmi, siggi, kalli, kula);
delete $names[2];
#@names is now: (hemmi, siggi, undef, kula).
- 3. At end
-
pop (@names);
#Element removed gets returned from function.
#So if you need to use that element you can write:
$var_at_end = pop (@names);
- 1. At beginning
- 2. List
- 1. Empty array
-
@temp = ();
- 2. From Loc X, Delete Y Many
-
@to_remove_from = qw(hemmi, kalli, siggi, joi);
splice(@to_remove_from, 1, 2);
#@to_remove_from is now: (hemmi, joi).
#If last argument is skipped the rest of the array will be removed.
- 3. Last X elements
-
#Last two:
splice @names, -2;
- 4. Newline From All Elements Of Array
-
chomp (@companies);
- 1. Empty array
- 1. Elements
- 9. Sort
- 1. Alphabetically
-
@nums_ordered = sort @nums;
#or:
#input and output arrays must be different arrays.
@sorted = sort { lc($a) cmp lc($b) } @not_sorted;
#which method is the real one needs to be tested.
- 2. Numeric
-
@nums_numerically_sorted = sort {$a <=> $b} @nums;
#In order to sort in reverse order, switch $a and $b.
- 3. Reverse
-
my @names = qw(hemmi, kalli, siggi, joi);
my @names_reversed = reverse @names;
#@names_reversed is now: (joi, siggi, kalli, hemmi).
- 1. Alphabetically
- 10. 2D
- 1. To 1D
-
@one_d_array = @{ $two_d_array[0] } [3..50];
- 2. Column quant in line
-
$col_quant=$#{$array[0]};
$col_quant++; $col_quant--;
#0 is the line number.
- 3. Get one column from 2d array
-
@one_column = map { $_->[0] } @the_array;
- 4. Put oned array into a twod array
-
@{$twod_array[-1]}=@oned_array;
- 1. To 1D
- 11. Copy
-
@data_new=map { [@$_] } @data;
deep copies an array.
copying arrays more complicated than one dimensional ones requires this method.
@one=@two; only copies the references within the arrays so you'll just end up with
two references to a single array.
- 1. Add
- 4. Hashes
- 1. Instantiate
- 1. Normally
-
%ages = ();
#A hash also gets instantiated if you just start filling it. (see Filling hash)
- 2. By rule
-
my @char_num{'A'..'Z'} = 1..26;
- 3. With preallocated memory (more speed)
-
keys(%somehash) = 40_000;#memory for 40.000 keys.
- 4. Hashes of arrays
-
%HoA = (
flintstones => [ "fred", "barney" ],
jetsons => [ "george", "jane", "elroy" ],
simpsons => [ "homer", "marge", "bart" ],);
- 1. Normally
- 2. Add
- 1. Elements manually
-
$ages{hemmi} = "27";
#The key "hemmi" now contains the value "27".
#If the key already had a value it will be overwritten.
#If key is composed of many words then you must put "" around it.
%days = (jan => 31, feb => 28);
#%days now contains keys jan and feb, and their values are 31 and 28. - 2. Conditionally
-
%days = (jan => 31, feb => $leap ? 28 : 29);
#%days will now have 28 days in februay IF $leap says its a leap year. - 3. Hashes
-
%all_names = (%names, %more_names);
- 4. Hash into an element of another
-
%{$big_hash{$somekey}} = %small_hash;
- 5. Nested hash keys from a list.
-
my @folders=(temp,usr,bin);
my %cpath; my $cpath_link=\%cpath;
for(my $cline=0;$cline<=$#folders;$cline++){
my $cfolder=$folders[$cline];
$cpath_link->{$cfolder}={};
if($cline==$#folders){$cpath_link->{$cfolder}=33;}
$cpath_link=$cpath_link->{$cfolder};
}
#here %the_path has gotten '{temp}{usr}{bin}'=33.
- 1. Elements manually
- 3. Get from
- 1. Number of keys
-
$x = keys %pairs;
#get element quantity in a hash
my $element_quantity = scalar keys %somehash;
- 2. All keys and all values
-
@list = keys (%companies);
@list = values (%companies);
- 4. Elements fitting criteria
-
#Get Hash Elements Where Both Key And Value Are Higher Than 100.
@largekeys = grep ( $_ > 100 or $numhash{$_} > 100 } keys %numhash.
- 5. In order of insertion
-
use Tie::Ixhash;
tie %HASH, "Tie::IxHash";
@keys = keys %HASH; #@keys is in insertion order.
- 6. Only in former
-
#subtract elements in %invalid_names from %names.
delete @names{keys %invalid_names};
- 7. Instance frequency
-
%count = ();
foreach $element (@array) {$count{$element}++;}
- 8. A hash within a hash of hashes, all keys
-
my @all_keys = keys %{$site_structure{tables}};
- 1. Number of keys
- 4. Print
- 1. Entire
foreach my $ckey (keys %cvar)
{
my $cvalue = $cvar{$ckey};
print STDOUT "$key\t$value\n";
}
- 2. One element
-
print $schedule{'monday'}->[1];
- 1. Entire
- 5. Remove
- 1. Element
-
undef $ages{hemmi};
#or
delete $ages{hemmi};
- 2. Keys also found in another hash
-
delete @names{keys %invalid};
- 3. Everything
-
%ages=();
- 4. An array within a hash.
-
delete ($thehash{thearray_within_it});
- 1. Element
- 6. Iterate through
- 1. Randomly
-
foreach $ckey (keys %cvar)
{
my $cvalue = $cvar{$ckey};
print STDOUT "$key\t$value\n";
}
- 2. By key
-
foreach $key (sort {$a <=> $b} keys %comp_score)
{print "$key, $comp_score{$key}\n";}
- 3. By value
-
foreach $key (sort {$comp_score{$b} <=> $comp_score{$a} } keys %comp_score)
{print "$key\t$comp_score{$key}\n";}
- 4. By value, numerically
-
%ages = (hmm=>1, siggs=>2, john=>23, anthony=>99, olav=>22, lila=>17);
foreach $key (sort { $ages {$a} <=> $ages {$b}} keys %ages )
{
print STDOUT "$ages{$key}\n";
}
- 1. Randomly
- 7. Switch keys and values.
-
%names_reversed = reverse %names;
- 8. To array
-
@temp = %temp;
- 9. Retrieve in insertation order
-
use Tie::IxHash;
# simple interface
$t = tie(%myhash, Tie::IxHash, 'a' => 1, 'b' => 2);
%myhash = (first => 1, second => 2, third => 3);
$myhash{fourth} = 4;
@keys = keys %myhash;
@values = values %myhash;
print STDOUT ("y") if exists $myhash{third};
- 10 Of arrays
- 1. Make
-
$somehash{"somekey"}[0] = $info[$count];
$somehash{"somekey"}[4] = $info[$count];
- 2. Add to
-
push @{ $somehash{"somekey"}[7] }, "wilma";
- 3. Make one array the key of another in a hash of arrays
-
#two arrays are aligned, make the elements in one of them the keys for the other.
#@the_keys = (1,1,1,2,2,2,3,3,3);
#@the_values = (olaf, siggi, helmet, bardar, ssa, aska, olav, olav, siggi);
#go into a hash like this:
#1 => olaf
#1 => siggi ...
#8 => olav.
for(my $cvalue=0; $cvalue<=$#the_values; $cvalue++)
{push @{ $the_keys{$the_keys[$cvalue]} }, "$the_values[$cvalue]";}
- 4. Sort hash by how many elements they have.
-
for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA )
{print "$family: @{ $HoA{$family} }\n"}
- 5. Iterate through.
-
foreach $cid ( keys %somehash )
{
my @cvalues = @{$id_info{$cid}}; #to get the whole array.
my @cvalues2 = $id_info{$cid}[1];#to get one element of the array.
}
- 6. Get size of
-
my $list_element_quantity = $#{$tree{0}{'list'}};
- 1. Make
- 11. Get key and all under it as a standalone hash
-
%key_one_and_all_under_it = %{$the_big_hash{1}};
#And to put it back:
$all_values_of_cpage{$ctable} = {%all_values_of_ctable};
- 12. Get size of array within a hash of hash
-
my $table_quantity = $#{$site_info{1}{tables}};
- 1. Instantiate
- 5. Structures
- 1. Make a hash of hashes
-
$hash{fruits} =
{
favorite => "apples",
'second favorite' => "oranges",
};
- 2. Make an array of hashes.
-
@array
(
favorite => "apples",
'second favorite' => "peas",
)
- 3. Make a hash of arrays.
-
%hash = (
fruits => ["apples", "oranges"],
vegetables => ["corn", "peas"],
)
- 4. Save and restore
-
use Storable;
@a1 = (
["apple", "orange"],
["asparagus", "corn"],
);
store (\@a1, "array.txt");
@a2 = @{retrieve("array.txt")};
- 5. Copy
-
@a2 = dclone(\@a1);
#@a2 is now a completely different copy of the dstructure.
- 6. Print
-
use Data::Dumper;
print Data::Dumper->Dump([\@array], [*array]);
- 7. Tie to a database
-
use Fcntl;
use NDBM_File;
tie %hash, "NDBM_File", 'data', O_RDWR, 0644;
while(($key, $value) = each(%hash))
{print "$key => $value\n";}
#to write to the database, just fill the hash.
- 1. Make a hash of hashes
- 6. Refs and Loops
- 1. Refs
- 1. To a var
-
$ref = \$var1;
- 2. To an array
-
$arrayref = \@temp;
- 3. To a subroutine
-
$subref = \&mysub;
@result = &$subref(1 .. 10);
- 1. To a var
- 2. Loops
- 1. For
-
#for (begin_value, condition_to_exit, value_change_per_iteration)
$total_individuals = 10;
for ($cind=0; $cind < $total_individuals; $cind++)
{print "Current individual is: "$current_individual""}
- 2. For with label
-
wjump:
for ($cind=0; $cind < $total_individuals; $cind++)
{last wjump;}#ends whatever loop started after wjump.
- 3. Foreach
-
foreach(@names)
{do something to every name in array. current-name is stored in $_.}
- 4. While
-
while (condition)
{do_something.}
while ($current_individual_no < 5)
{print "We have sill not reached the fifth individual."}
- 1. For
- 1. Refs
- 7. Functions
- 1. About
-
Functions have two purposes:
- To allow you to reuse your code by refering to it later.
- To make your code easier to understand.
The function name can describe an overall working of many lines.
Procedure, method, subroutine and function all mean the same thing.
I use the word function for its used the most.
Argument is what you send to a function when you call it, for example:
get_average(@values); #@values is the argument here.
If you send no arguments to a function, @_ will be sent.
Last statement in a function gets returned unless specifically stated with "return".
Lexical = only in this function.
Dynamic = goes down.
- 2. Naming them
-
When namking functions make sure they:
-do what they say they do,
-all of what they say they do,
-and nothing but what they say they do.
Also, all words used by functions should have a very clearly understood meaning.
Their assumption should be kept at a minimum.
The little assumptions you cannot avoid making, state them clearly at the beginning of the function.
the less assumptions, the better the function.
- 3. Remember var values from last run
-
sub BEGIN
{
my $count = 0;
sub inc{return ++$count;}
print inc;
print inc;
}
prints 1,2
- 4. Bracket usage
-
$average = get_average(@ages);
#Will work the same as:
$average = get_average @ages; - 5. Arguments
- 1. Catch
-
#Inside function:
$first_arg = shift;
$second_arg = shift;
- 2. Make default
-
$age ||= 3;
#im having difficulties getting this to work though.
- 3. Specify possible
-
sub subname ($$;@);
#Means two $ are mandatory, one @ is optional.
- 4. Passing by reference
-
@a = (1,2,3);
@b = (4,5,6);
sub addem
{
my ($ref1, $ref2) = @_;
while (@$ref1){unshift @result, pop(@$ref1) + pop(@$ref2);}
return @result;
}
@array = addem(\@a, \@b);
- 5. Complex arguments
-
#function below can receive three structs, one hash, one array and one var:
sub somefunc
{
my %args = @_;
my %some_hash = %{$args{hash_sent_in}};
my @some_array = @{$args{array_sent_in}};
my $some_variable = $args{var_sent_in};
#here, array, var and hash have all been filled.
}
#now i can call the function in the following manner:
somefunc(array_sent_in=>[@some_array], hash_sent_in=>{%some_hash}, var_sent_in=>$some_variable);
- 1. Catch
- 6. Info
-
@info = caller();
- 7. Optimize
-
inlined functions are optimized for speed.
they must consist of either a constant or a lexically scoped scalar. ?
the function may not be referenced with & or do.
- 8. Return
- 1. Multiple structures
-
($array_ref, $hash_ref) = somefunc();
sub somefunc
my @array;
my %hash;
return (\@array, \%hash);
- 2. By itself
-
return alone returns undef.
undef is often interpreted as a failure of running function.
- 1. Multiple structures
- 1. About
- 8. Modules
- 1. About
-
A module is a text file which contains a pile of functions which belong together.
- 2. Making
-
#1. Create a text file, give it a .pm extension.
#2. Fill it with the following:
package Module-name;
require Exporter;
our $VERSION = 1.00;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw($weight); #can be exported but will not be automatically.
our @EXPORT = qw
(
the_name_of_your_first_function
);
sub the_name_of_your_first_function
{
#Here you write your reusable, well named code snippet.
print STDOUT "Holy shit ive made a function.\n";
}
#Once a module has been made you can give a script access to it by typing "use Module-Name" in the script.
#Now that script can use the functions of the module.
- 3. Installing
- 1. From CPAN
-
Go to command prompt(cmd).
type "ppm" (takes you to Perl Package Manager)
type "search <module-name>"
type "install <module-name>"
Options in ppm:
help: prints a list of choices.
search: shows packages you have available to install.
query: shows packages you have already installed.
install: install a specific package.
verify: make sure your packages are up to date.
remove: remove a specific package.
- 2. GD::GRAPH
-
#Type the following commands in cmd:
ppm install http://theoryx5.uwinnipeg.ca/ppms/GD.ppd
ppm install http://theoryx5.uwinnipeg.ca/ppms/GDTextUtil.ppd
ppm install http://theoryx5.uwinnipeg.ca/ppms/GDGraph.ppd
ppm install http://theoryx5.uwinnipeg.ca/ppms/GD-Graph3d.ppd
- 3. Check if a specific module is already installed
-
perl -e "use module-name;"
#Might only work in Unix.
- 1. From CPAN
- 4. Get Perl to search in more paths for modules
-
set PERL5LIB=/path-to-your-new-modules/
- 5. Get current module
-
Variable __PACKAGE__ contains the name of the current module.
- 6. Get module information
-
perldoc <module-name> #(in cmd)
- 7. Lib
-
use lib'c:/some-folder/module-name/';
use ModuleName;
- 1. About
- 9. Handles/Files
- 1. Information
- 1. Get all files *.c and calculate memory they all take
-
for (<*.c>) {$bytes += -s;}
- 2. Get files smaller than 5KB
-
@small_txt = grep { /\.txt\Z/ and (-s) < 5000 } @files;
- 3. Get filenames at path
-
use Cwd;
my $cwd=cwd;
chdir "$cwd"; opendir($cwd, ".") or die "$!";
@pathfiles_and_directories_here=grep {/.*/} readdir CDIR; foreach(@pathfiles_and_directories_here) {$_="$cwd"."/$_";}
close CDIR;
#beware, glob is known to fail when folder names include spacebar.
#@a = </etc/host*>
#@files = glob '*.pl';
- 4. Get information about a file
-
@stats = stat("somefile.pl");
#@stats now has:
#1.Device number of file systems
#2.inode number
#3.file type and permissions
#4.hard link quantity
#5.owners UID
#6.owners group number of UID
#7.device identifier
#8.total size in bytes (gives a weird number in linux at least)
#9.last access time
#10.last modification time
#11.inode change time
#12.preferred block size for file system IO
#13.actual number of blocks allocated
#-M = age in days since the filehandle was modified.
Open (WORDSLIST, “wordslist”)
If (-M WORDSLIST >= 7.0)
- 5. Change rights to file
-
while (<*.c>){chmod 0644, $_;}
- 6. Know if a file is there
-
if(!(-e "pathandfile"))
{
print STDOUT "The pathfile does not exist.\n";
}
- 1. Get all files *.c and calculate memory they all take
- 2. Manipulation
- 1. Filehandles
- 1. Write into a filehandle/file
-
open (W_FILE, ">>C:/somefolder/somefile.txt") or die "Path does not exist.\n\n";
# The above tries to make a file at the given path, or notifies otherwise.
#> Overwrites the document.
#>> Adds to the document.
#now you can type to that specific file by typing:
print W_FILE "Hey, this text is going straight to the file.\n";
#when typing large amounts:
print <<EOD;
This is a
here doc.
EOD
#The computer does not write your text to the file until you close the filehandle.
#That happends automatically at the end of every program, or you can do it manually:
close W_FILE;
- 2. Read from a filehandle/file
-
open(MYINPUTFILE, "<C:/somefolder/somefile.txt") or die "Could not open file, maybe folder does not exist.\n\n";
while(<MYINPUTFILE>)
{
#Good practice to store $_ value because subsequent operations may change it.
my($line) = $_;
#Good practice to always strip the trailing newline from the line.
chomp($line);
#Convert the line to upper case.
$line =~ tr/[a-z]/[A-Z]/;
#Print the line to the screen and add a newline
print "$line\n";
}
- 3. Make a filehandle default
-
select STDOUT;
#Now you can type: print "hey there";
#and it works as if you had typed: print STDOUT "hey there";
- 4. Set/see filehandle position
-
#Makes position in file become 12.
seek Filehandle, 12, 0;
#prints 12.
print tell Filehandle;
- 5. Lock file
-
#lock files from other processes.
flock FILEHANDLE, OPERATION
LOCK_SH = share the file, 1
LOCK_EX = use it exclusively, 2
LOCK_NB = 4
LOCK_UN = unlock 8
- 1. Write into a filehandle/file
- 2. Copy files
-
use File::Copy;
copy ("file.txt", "file2.txt");
- 3. Move files
-
move ("datafile.dat", "datafile.bak");
- 4. Delete files
-
#Unlink returns number of files successfully deleted.
unlink ("fred");
- 5. Rename files
-
rename ("file","some-directory/file");#moves the file?
rename (old_filename, new_filename);
- 6. Operate on files by pattern
-
unlink <*.O>
- 7. Insert an entire file into a variable
-
open(RFILE, "<$filename") or die "Could not open file, maybe folder does not exist.\n\n";
while(<RFILE>){$filecontent .= $_;}
#Or u can sue the Slurp module for a bit greater clarity:
use File::Slurp;
my $thefile = read_file($file);
- 1. Filehandles
- 1. Information
- 10. Directories
- 1. Get current working directory
-
use Cwd; $cwd=cwd(); #now $cwd has current working directory.
- 2. Change current working directory
-
Chdir "C:\\Windows\\temp\\";
#if the path doesnt exist, there will be an error. - 3. Make directory
-
#Makes directory hemmi with access rights 0777.
#Creates it under your current working directory.
mkdir("hemmi",0777); - 4. Delete directory
-
#Use with extreme caution. It could format your harddrive.
use File::Path;
rmtree($to_delete); - 5. Break pathfile into path and file
-
use File::Basename;
my $pathfile = "C://task//language.txt";
my $path = basename($path);
my $file = dirname($path);
#Now $base is "C://task//" and $dir is "language.txt".
- 6. See if directory exists.
-
if(-d c:/somedirectory/)
{print STDOUT "That directory exists.\n";}
- 7. Go through all subfolders
-
use File::Find;
find(\&make_album, "C:/mydocs/lab/album_viewer");
#function make_album will now be called with every subfolder under the path given.
#the following function will tell you every subfolder there is to the path you send in:
sub make_album_page
{
my $temp = $ENV{PWD};
my $cpath = $File::Find::dir; #the path.
#$_ = current file.
#$File::Find::name = #cpath and file.
#if this folder is unseen, tell about it.
unless (defined $seen{$cpath})
{$seen{$cpath} = 1;print STDOUT "Working at $cpath\n";}
}
- 8. Get shell commands output into perl
-
$cw = 3;
$folder_three_slash_keys = "$cw".'/keys';
$files_line_quantity = `wc -l < ~/some_folder/$folder_three_slash_keys`;
- 1. Get current working directory
- 11. Web/Network
- 1. Get links
-
You get them.
- 2. Get photos
-
use LWP::Simple;
getstore("http://www.somedomain/somepicture.jpg", "filename.jpeg");
- 3. Send email
-
my $email = Net::SMTP->new('adomain.cz'); #contact your internet provided to get your domain.
$email->mail('somebody@gmail.com');
$email->to('somebody@gmail.com'); $email->data();
$email->datasend("hello ya");
$email->dataend(); $email->quit;
- 4. Getting rid of %xx in url paths
-
#to decode for example.. %C7 in urls..
$url_content =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
- 5. Get url
-
use LWP::Simple;
$url_content = get($url_address);
- 6. Get url info
-
use LWP::Simple qw(!head);
use CGI qw(:standard);
@information_about_url = LWP::Simple::head("www.someurl.com");
$size_of_url = $information_about_url[1];
#array information_about_url now contains a lot of information about the url.
- 7. Get a DNS address
-
#getting a DNS address.
use Socket;
$site_name = "www.cpan.org";
$address = inet_ntoa(inet_aton($site_name));
- 8. FTP-ing
-
use Net::FTP;
$ftp = Net::FTP->new("ftp.cpan.org",Timeout => 30);
$username = "anonymous";
$password = "steve";
$ftp->login($username, $password);
$ftp->cwd('/pub/CPAN');
$remotefile = "CPAN.html";
$localfile = "file.txt";
$ftp->get($remotefile, $localfile);
- 9. Pinging
-
use Net::Ping;
$pingobject = Net::Ping->new(icmp);
if ($pingobject->ping('cpan.org')){print STDOUT "Reached CPAN.";}
$pingobject->close();
- 10. Telnetting
-
use Net::Telnet;
$telnet = Net::Telnet->new(Timeout => 90, Prompt => '%', Host => 'somedomain.com');
$telnet->login('username', 'password');
$telnet->cmd("cd hemmi");
@listing = $telnet->cmd("ls");
print STDOUT "@listing";
- 1. Get links
- 12. Text manipulation
- 1. Character classes[]
- 1. User defined
-
[123] will match 1 or 2 or 3.
[0-9] will match any digit.
[abcdef] will match a or b or c or d or e or f.
[a-z] will match any small letter.
[a-zA-Z] will match any letter, big or small.
[^123] will match any letter except for 1 or 2 or 3.
- 2. Pre-defined
-
\d = [0-9].
\D = [^0-9].
\w = [a-zA-Z].
\W = [^a-zA-Z].
\s = [ ]. (includes newline)
\S = [^ ].
\A = Beginning of line.
\Z = End of line.
\b = Word boundary.
\B = Not word boundary.
. = Any character, except \n. (Putting /s at the end will include it.)
Within [] \ makes whatever comes next be interpreted literally.
[\^] = matches the character ^.
[\^$] = matches ^ or $.
\Uhemmi\E #Turns hemmi into HEMMI
\LHEMMI\E #Turns HEMMI into hemmi
\uhemmi #Turns hemmi into Hemmi
- 3. Examples
- 1. The content the examples are in
-
$name = Hermann;
if ($name =~ s/heres_pattern/heres_whats_replaced_with/g;)
- 2. This or that
-
/th(is|at)/
#Matches: this or that.
- 2. pet, get, met, set or bet
-
[pgmsb]et
- 3. bear where the a is optional
-
/bea?r/
#Matches: bear or ber.
- 4. Not followed by
-
#Not followed by "msSmall".
(?!\"msSmall\")
- 5. Get nth occurrence of
-
$want = 3;
$count = 0;
while (/(\w+)\s+fish\b/gi)
{
if (++$count == $want)
{
print "The third fis is a $1 one.\n";
}
- 1. The content the examples are in
- 1. User defined
- 2. Substitution
- 1. Options
-
s/something//gimsox;
g = find all occurrences.
i = case insensitive.
m = treat string as multiple lines, ^ and $ embed \n.
s = treat string as a single line.
o = only interprets vars once. (faster but is bad if the var changes value.)
x = use extended regular expressions.
- 2. Quantifiers
-
#Greed = matching as many as you can.
{0,} = Match 0 or more times.
{1, 4} = Match 1 to 4 times.
* = {0,}. #(greedy)
+ = {1,}. #(greedy)
*? = {0,}. #(not greedy)
+? = {1,}. #(not greedy)
/Hermann*/
Matches: Herman, Hermann, Hermannnnnnnnn.
- 3. Brackets
- 1. Determine sequence
-
#Whatever is inside the brackets gets executed before whats outside of them.
#Example:
$outcome = 3 * (4 + 3);
#$outcome will be 3 * 7, or 21.
- 2. Store bracket content in $no.
-
#Whatever is inside brackets gets stored in $1, $2, $3 etc.
s/(this|that)/\U$1/g;
#Will substitute this or that with THIS or THAT. Whichever it was.
If you put ?: into your brackets they will not be saved into $no.
s/(?:[a-c])m(e)n/$1/;
#Substitutes amen, bmen, cmen with e.
- 1. Determine sequence
- 4. Hidden vars
- 1. The english module
-
When doing substitution in Perl many hidden vars get automatically filled.
Following are some of those variables.
$0 = Program name. $+ = $LAST_PAREN_MATCH; #Is the last $n that matched.
$\ = $OUTPUT_RECORD_SEPARATOR.
$' = $POSTMATCH;
$& = $MATCH;
$` = $PREMATCH;
$. = $INPUT_LINE_NUMBER;
$+ = last expression.
$= = number of lines on page.
$. = current line no.
$- = lines left of the current page.
$^O = OS being used.
$^T = time when script began running.
$^X = path of script.
- 2. Other
-
#$_ is the default variable which always gets filled.
#Example:
foreach (@names)
{#On each iteration $_ will be filled with the current element in @names.}
- 1. The english module
- 5. Examples
- 1. The most basic example
-
$name = "Hermann Jens";
#if name contains "ann":
if ($name =~ /ann/)
{print "Yes his name contains 'ann'.\n";}
- 2. Get loc where var contains pattern
-
#Records all locations where the number three is found in the var.
$find = "123 345 456 346";
while ($find =~ /3/g)
{
# $& = current string matched.
@positions = (@positions, pos $find);
}
- 3. Match where pattern1 is not followed by pattern2
-
/blue(?!bird)/
#"bluebox" and "bluesy" will be matched, but not "bluebird".
- 4. Change the default variable ($_)
-
$_ = "secret message";
tr/n-za-m/a-z/;
- 5. Match content of quotes
-
/"([^"]+)"/
- 6. Pre and postmatch
-
$text = "earlynowlate";
$text =~ /now/;
print "Prematch: \"$`\" Match: \"$&\" Postmatch; \"$'\"\n";
- 7. Remove trailing and preceding whitespaces.
-
$to_remove_from =~ s/^\s*//; #removes leading spaces
$to_remove_from =~ s/\s*$//; #removes trailing spaces
- 8. Getting columns from a table.
-
my $td = "<td[^>]*>(.*?)<\/td>";
my @cline = map { /$td+/gi } $cline_html;
- 9. Use RE in substitution
-
#my $the_substitution = '$string =~ s/'."$crule"."/$sub_rules{$crule}".'/gi;';
#eval "$the_substitution";
- 1. The most basic example
- 1. Options
- 3. Print correct plurals
-
use Lingua::EN::Inflect qw(PL classical);
classical(1);
while(){for (split){print "One $_, two ", PL($_), ".\n";}}
__END__
fish fly ox
species genus phylum
cherub radius jockey
index matrix mythos
phenomenon formula
#This prints a lengthy text where the plurals are always correct.
- 1. Character classes[]
- 13. Graphics
- 1. Tk (buttons, scrollbars etc.)
- 1. Tree
-
#!/usr/bin/perl
use Tk;
use Tk::Tree;
my $mw = MainWindow->new(-title => 'Perl To The Point');
my $tree = $mw->Tree->pack(-fill => 'both', -expand => -1);
$tree->add("P", -text => "Perl");
$tree->add("P.2", -text => "Getting started");
$tree->add("P.2.1", -text => "Go to www.activestate.com\n and say hi");
$tree->add("P.3", -text => "Arrays");
$tree->add("P.3.1", -text => "Instantiate an array");
$tree->add("P.4", -text => "Hashes");
$tree ->autosetmode();
MainLoop;
- 1. Tree
- 2. GD
-
later
- 3. Graphs
-
later
- 4. ImageMagick
-
never, EVER, use crop through Perl's ImageMagick in code.
It fails at random times.
Use convert from the shell instead:
my $crop_string='convert image_1.png -crop 100x100+0+0 image_2.png';
system "$crop_string";
- 1. Tk (buttons, scrollbars etc.)
- 14. Miscellaneous
- 1. General knowledge
- 1. The undervalued art of good naming
-
Having the names of "variables/arrays/hashes/functions" clear and highly
descriptive of their content is much more important than most people realise.
I dont want to think about all the days ive spent looking for errors that were
caused by poor naming.
- 2. C to Perl comparison
-
Perl is slow at math, but number crunching applications dont do that much math.
Instead they spend a lot of time reading the input and formatting the
output with a little number work in the middle.
Perl is excellent for the beginning and end of this process.
Optimum performance would be reached by using Perl in the beginning and the and, and using C in the middle.
- 1. The undervalued art of good naming
- 2. Time
- 1. Sleep
- 1. Sleep for x seconds
-
sleep x;
- 2. Sleep for a fraction of a second
-
Use Time::HiRes qw(sleep);
Sleep (0.3);
#might be platform dependent.
- 1. Sleep for x seconds
- 2. Dates
- 1. Get current date
-
@time = localtime();
#Now @time contains the following:
$time[0] = Seconds past the minute.
$time[1] = Minutes past the hour.
$time[2] = Hours past midnight.
$time[3] = Day of the month.
$time[4] = Months past the start of the year.
$time[5] = Number of years since 1900.
$time[6] = Number of days since the start of the week (Sunday).
$time[7] = Number of days since the start of the year.
$time[8] = Wether or not daylight savings is active.
- 2. Get date derivations
-
use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);
#$year, $month and $day are assumed to be filled.
$wday = Day_of_Week($year, $month, $day);
$wnum = Week_Number($year, $month, $day);
$dnum = Day_of_Year($year, $month, $day);
use Date::Calc qw(Delta_DHMS);
($days, $hours, $minutes, $seconds) =
Delta_DHMS($earlyyear, $earlymonth, $earlyday, $earlyhour, $earlyminute, $earlyseconds, $lateral);
Add_Delta_DHMS(2001, 12, 31, 23, 59, 59, 0, 0, 0, 1);
#puts date into 2002.
- 2. Get difference between two dates
-
use Date::Calc qw(Delta_DHMS)
($days, $hours, $minutes, $seconds) =
Delta_DHMS
($year1,$month1,$day1,$hour1,$minute1,$seconds1,
$year2,$month2,$day2,$hour2,$minute2,$seconds2);
- 1. Get current date
- 3. Epoch seconds
-
$epoch_time = time;
#time represents number of seconds since jan.1st 1970.
- 5. Measure cpu strain
-
use Benchmark;
$timestamp2 = new Benchmark;
$timedifference = timediff($timestamp2, $timestamp1);
print "The look took: ", timestr($timedifference);
- 6. Measure cpu strain II
-
use Time::HiRes qw(gettimeofday);
system "cls";
$t_bef = gettimeofday;
$wrote = V>P;
$t_aft = gettimeofday;
$t_taken = $t_aft - $t_bef;
- 7. Stop if action takes too long
-
alarm(5); #resets everything if time is passed.
- 1. Sleep
- 3. DOS
- 1. Running DOS commands in Perl
-
#within a perl script do:
system "somefile.exe";
- 2. Perl one-liners
- 1. Run
-
#Start->run
#type "cmd".
#Now you are in command prompt (DOS).
#type: perl -e "print \"Hello World\n\";"
#prints: Hello world.
#This way you can write perl scripts directly through DOS.
#You just have to write them in one line.
- 2. Bat files
-
#Bat files operate in "cmd" and execute commands as if they were typed in by user.
#How to make them:
#Make a document and label it "something.bat".
#Edit it by opening it up with a text editor.
#Write whatever commands you want to be executed in "cmd" once it runs.
#Save it to a path of your choice.
#Go into command (start->run and type "cmd"):
#Go to the path where the bat file is stored.
#Type name of bat-file, without the extension.
- 3. Pause monitor output
-
perl report.pl |more
- 1. Run
- 3. Shutting down the computer
-
system("shutdown -h now");
- 4. Restarting the computer
-
system("shutdown -r now");
- 1. Running DOS commands in Perl
- 4. Complex data structures
- 1. Print
-
require "dumpvar.pl";
dumpvalue(\@date_array);
- 2. Copy
-
use Storable qw(dclone);
my $new_array_ref = dclone(\@date_array);
#Also makes a copy of what the data-structure refers to.
- 3. Retrieve from a file
-
use Storable qw(nstore, retrieve);
$href = retrieve("filename");
#or
%hash = %{ retrieve("filename") };
- 1. Print
- 5. Change tab value
- 1. In Textpad
-
View-Document Properties-Tabulation
There you can change TAB value.
- 2. In Crimson
-
Tools-Preferences-General.
The top right part of the screen.
- 1. In Textpad
- 7. Monitor
- 1. Receive input from user
-
$name = <STDIN>;
print STDOUT "Hello $name\n";
- 2. Keeping the console open
-
#to keep the console window open after program finishes executing,
add <> at the end.
- 1. Receive input from user
- 8. Windows executables
-
Executable guide
for linux:
see: this
i did: 'pp -o hemmi.exe hemmi.pl'
- 9. Bizarre error messages and what they actually mean
- 1. Global symbol @ISA requires explicit package name.
-
Actually means:
Calling script needs to add a use statement concerning the module the error came from.
- 1. Global symbol @ISA requires explicit package name.
- 10. Testing
- 1. To test code rapidly
-
#Run the following code and then youll be able to run code from cmd.
my $count = 0;
my $statement = "";
local $SIG{__WARN__} = sub{};
while (<>) #access input from the keyboard.
{
chomp;
while (/{|\(|\[/g) {$count++;}
while (/}|\)|\]/g) {$count--;}
$statement .= $_ . " ";
if (!$count)
{
eval $statement;
if ($@) {print "Syntax error.\n";}
$statement = "";
$count = 0;
}
}
- 1. To test code rapidly
- 12. Windows <=> UNIX
- 1.The carriage return problem
-
#remover
$infile = $ARGV[0];
$outfile = $ARGV[1];
open (INFILEHANDLE, "<$infile");
open (OUTFILEHANDLE, ">$outfile");
binmode INFILEHANDLE, ":crlf";
binmode OUTFILEHANDLE, ":raw";
while (defined($line =)){print OUTFILEHANDLE $line;}
close INFILEHANDLE;
close OUTFILEHANDLE;
#adder
just switch the binmodes.
- 1.The carriage return problem
- 13. Formatting text
- 1. Set max col quantity
-
use Text::Wrap qw(wrap $columns);
$columns = 12;
print wrap("", "", "TEXTHERE");
#text now gets printed with never more than max columns per line.
- 1. Set max col quantity
- 14. Databases
- 1. Connect to DB
-
use DBI;
$dbh = DBI->connect(
'DBI:mysql:databasename:localhost:3306',
'root',
'',
{ PrintError => 1, RaiseError => 1})
or die "connecting: $DBI::errstr";
- 1. Connect to DB
- 1. General knowledge