Saturday, June 28, 2014

Usage of FindBin and Require Module

FindBin
We can use FindBin to locate the directory of our Perl script.
This can then be used, if required, to specify locations of required files stored relative to that script.

use FindBin qw($Bin);

# require the example.pl in the same directory as our script
require "$Bin/example.pl";

# require the other.pl file in the files/ directory
require "$Bin/files/other.pl"

RequireRequired files must end with a true value.
This is usually achieved by having the final statement of the file being:
1;

Thursday, June 19, 2014

Change Input record separator


Change input record separator


$/=undef; #Read the whole file in at once
$/=""; #Read in paragraph by paragraph
$/="\n%\n"; #Read in Unix fortunes

<> operator


<> is a highly magical operator. First it checks @ARGV to see if there are arguments to use a filename.
If there are, it will open each file in order, and iterate through each line.
If @ARGV is empty, it checks for input on STDIN.

Perl Class Tutorial


1. Class:
A Class is a blueprint of object
A class is just a package containing methods
2. Object:
An Object is Instance of the class (properties)
An object is just a reference with an associated class
3. Method:
    A method is just a subroutine which takes an object or class as its first argument
4. Inheritance:
    Reuse the base class method (definition)
New class from an existing class
5. Encapsulation:
    Information hiding

 

6. Abstraction:
    View the essential details
7. Polymorphism:
Many forms
Ex: Human being
Type:
1. static – overloading – Same method but passed different parameter
        Ex: my $half  = Number::Fraction->new(1, 2);
        my $quarter   = Number::Fraction->new(1, 4);

 
2. dinamic – overriding – If derived class and base class  have the same method, to get the derived class.
8. Autoloading:
    In case, we can call an undefined subroutine, in that time called already defined autoload function, it's through an exception.
If a subroutine named AUTOLOAD is declared within a package, it is called whenever an undefined subroutine is called within the package.

9. Bless:
bless associates a reference with a package
    Bless only works on references

10. What is the difference between package, module and class in object oriented Perl

    Modules are a single file, a .pm file that provides code. That could be no packages, a single package, or more than one package. A module doesn't really care what is in it, so it can be code that inserts itself into the same namespace, a more-traditional set of subroutines in a library, or define Perl's idea of a class.

A package, also known as a namespace, contains its own variables and subroutines.
11. In Perl, what is the difference between use and require for loading a module?

use runs at compile time, and require runs at run time.
12. What's the difference between Perl's backticks, system, and exec?

exec

executes a command and never returns. It's like a return statement in a function.
If the command is not found execute returns false. It never returns true, because if the command is found it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.
system

executes a command and your perl script is continued after the command has finished.

The return value is the exit status of the command. You can find documentation about it in perlfunc.
backticks

like system executes a command and your perl script is continued after the command has finished.
In contrary to system the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and execit is an operator.
13. What's the difference between exists and defined?

    defined $hash{key} tells you whether or not the value for the given key is defined (i.e. not undef). Use it to distinguish between undefined values and values that are false in a boolean context such as 0 and ''.
defined checks the value of the variable
exists $hash{key} tells you whether or not %hash contains the given key. Use it to distinguish between undefined values and non-existent ones.
14. What's the difference between return; and return undef; in Perl

    return will return an empty list in list context but undef in scalar context. return undef; will always return a single value undef even in list context.
15. What is the difference between my and our in Perl?

    Great question: How does our differ from my and what does our do?
In Summary:

Available since Perl 5, my is a way to declare:
  • non-package variables, that are
  • private,
  • new,
  • non-global variables,
  • separate from any package. So that the variable cannot be accessed in the form of $package_name::variable.
On the other hand, our variables are:
  • package variables, and thus automatically
  • global variables,
  • definitely not private,
  • nor are they necessarily new; and they
  • can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.
16. What is the difference between DBI and DBD?

    DBI is database access library, whereas DBDs are "drivers" which are used by DBI to access particular database (eg. there is one DBD for MySQL, another one for PostgreSQL etc). You should use DBI rather than DBDs directly.
17. In Perl, what is the difference between @array[1] and $array[1]?

    $ and @ are called sigils: hear what the sigils tell you

When you see $ you are dealing with a single thing. When you see @ you have a list of things.
@array[ 1 ] is a slice, a list with selected elements from the @array list. You have put only an element in this slice, the second element of @array, but it's a list anyway.
$array[ 1 ] is the second element of the list, a single value, a scalar.
@hash{ 'one', 'two' } is another kind of slice: this time we sliced an hash ( %hash ), obtaining a list with values corresponding to keys one and two.
18. What is the difference between `$this`, `@that`, and `%those` in Perl?

$this is a scalar value, it holds 1 item like "apple"
@that is an array of values, it holds several like ("apple", "orange", "pear")
%those is a hash of values, it holds key value pairs like ("apple" => "red", "orange" => "orange", "pear" => "yellow")
19. What is the difference between "||" and "or" in Perl?

  •     OR
This is list operator . On the right side of a list operator, it has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators "and", "or", and "not", which may be used to evaluate calls to list operators without the need for extra parentheses. Logical or, Defined or, and Exclusive Or

$a = $b or $c;          # bug: this is wrong
($a = $b) or $c;        # really means this
$a = $b || $c;          # better written this way
@info = stat($file) || die;     # oops, scalar sense of stat!
@info = stat($file) or die;     # better, now @info gets its due
  • ||
If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. For example, because named unary operators are higher precedence than ||:

chdir $foo    || die;   # (chdir $foo) || die
chdir($foo)   || die;   # (chdir $foo) || die
chdir ($foo)  || die;   # (chdir $foo) || die
chdir +($foo) || die;   # (chdir $foo) || die
20. What is the difference betweeen %INC and @INC?

The @INC array holds all the file system paths where Perl will be looking for modules when you use or require them.
After use or require, the %INC hash will contain the loaded modules and where they were loaded from.
Examples from my laptop:
@INC:
'/etc/perl',
'/usr/local/lib/perl/5.10.0',
'/usr/local/share/perl/5.10.0',
'/usr/lib/perl5',
'/usr/share/perl5',
'/usr/lib/perl/5.10',
'/usr/share/perl/5.10',
'/usr/local/lib/site_perl',
'.'
and %INC:

'warnings/register.pm' => '/usr/share/perl/5.10/warnings/register.pm',
'bytes.pm' => '/usr/share/perl/5.10/bytes.pm',
'XSLoader.pm' => '/usr/lib/perl/5.10/XSLoader.pm',
'Carp.pm' => '/usr/share/perl/5.10/Carp.pm',
'Exporter.pm' => '/usr/share/perl/5.10/Exporter.pm',
'warnings.pm' => '/usr/share/perl/5.10/warnings.pm',
'overload.pm' => '/usr/share/perl/5.10/overload.pm',
'Data/Dumper.pm' => '/usr/lib/perl/5.10/Data/Dumper.pm'
(%INC contains Data::Dumper because I used it to quickly dump those two values).

21. What is the difference between my and local in Perl?

    'my' creates a new variable, 'local' temporarily amends the value of a variable.
ie, 'local' temporarily changes the value of the variable, but only within the scope it exists in.
22. What's the difference between an object and a class in Perl?

There are lots of "a class is a blueprint, an object is something built from that blueprint.

What is a Module


What is a Module

  • Has a filename ending with '.pm' and a package name to match
  • If the filename is in a lower directory, the package name uses '::' for the directory separator
The Barest of Modules

  • package gives the name of the module
  • The filename would be Sample/Module.pm and the Sample directory will live in one of the directories listed in @INC
use Exporter

  • The Exporter module makes the changes to symbol tables to export functions and variables from one package to another
use vars

  • These are package variables needed to make Exporter happy
  • $VERSION is also known as $Sample::Module::VERSION
$VERSION

  • Required variable
  • Should be a real number like 0.1 or 2.9996
  • Should not be like LINUX kernal numbering 2.2.4 with extra periods
@ISA

  • Modules to inherit variables, methods, and functions from
@EXPORT


 


 

  • Functions and Variables here are exported by default. They will pollute the name space of the package that calls this module and can be called without a package name
  • Give a Hoot, Don't Pollute. Only export by default those things that really need it.
@EXPORT_OK

  • Functions and Variables here are exported only if requested.
  • Otherwise they can still be used, but you must give the full name like $Sample::Module::Foo
  • my variables can not be exported, must use vars
%EXPORT_TAGS


 


 

  • Pre-defined groups of things to export. All functions and variables included must also be in either @EXPORT or @EXPORT_OK.
@EXPORT_FAIL


 


 

  • List of things to never ever export
1

  • All modules (and required files) need to return a true value. The simplest way to guarantee a true value is to end the module with a "1;", which is true.
__END__

The "__END__" tells Perl to ignore anything after it. If you have documentation or retired functions you can't yet throw away, it is easy to leave them after the "__END__" where they will do no harm.