Showing posts with label Perl Functions. Show all posts
Showing posts with label Perl Functions. Show all posts

Monday, 17 November 2014

Fetch Uniq elements from the array efficiently using grep or hash

Through hash:

my %faculty_hash = ();
foreach my $facs (@faculty) {
  $faculty_hash{$facs} = 1;
}
my @faculty_unique = keys(%faculty_hash);


Please note: Some of the answers containing a hash will change the ordering of the array. Hashes dont have any kind of order, so getting the keys or values will make a list with an undefined ordering.
To preserver the order of the elements use grep:


my %seen;
my @unique = grep { ! $seen{$_}++ } @faculty;

Other ways:
use List::MoreUtils qw/ uniq /;
my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}


Reference: 

http://stackoverflow.com/questions/439647/how-do-i-print-unique-elements-in-perl-array 

Thursday, 13 November 2014

Perl Time formatting using strftime

use POSIX qw(strftime);
my $currentTime = strftime "%Y-%m-%d %H:%M:%S", localtime; 


Thursday, 18 August 2011

waitpid($childpid,0)

process is running: waitpid returns 0; $? is -1
process is exiting: waitpid returns pid; $? is actual exit code
process doesn't exist: waitpid returns -1; $? is -1

so we need $? when waitpid returns childpid
we need to grab $? separately from $ret=waitpid($childpid,0)
$ret will return 0, pid or -1

Tuesday, 26 July 2011

use,require,do,my and local


  • my() vs. use vars:

    With use vars(), you are making an entry in the symbol table, and you are telling the compiler that you are going to be referencing that entry without an explicit package name.

    With my(), NO ENTRY IS PUT IN THE SYMBOL TABLE. The compiler figures out at compile time which my() variables (i.e. lexical variables) are the same as each other, and once you hit execute time you cannot look up those variables in the symbol table.

  • my() vs. local():

    local() creates a temporal-limited package-based scalar, array, hash, or glob -- that's to say, when the scope of definition is exited at runtime, the previous value (if any) is restored. References to such a variable are also global ... only the value changes. (Aside: that is what causes variable suicide. :)

    my() creates a lexically limited nonpackage-based scalar, array, or hash -- when the scope of definition is exited at compile-time, the variable ceases to be accessible. Any references to such a variable at runtime turn into unique anonymous variables on each scope exit.

use(), require(), do(), %INC and @INC Explained

The @INC Array

@INC is a special Perl variable that is the equivalent to the shell's PATH variable. Whereas PATH@INC contains a list of directories from which Perl modules and libraries can be loaded. contains a list of directories to search for executables,

When you use(), require() or do() a filename or a module, Perl gets a list of directories from the @INC variable and searches them for the file it was requested to load. If the file that you want to load is not located in one of the listed directories, then you have to tell Perl where to find the file. You can either provide a path relative to one of the directories in @INC, or you can provide the full path to the file.

The %INC Hash

%INC is another special Perl variable that is used to cache the names of the files and the modules that were successfully loaded and compiled by use(), require() or do() statements. Before attempting to load a file or a module with use() or require(), Perl checks whether it's already in the %INC hash. If it's there, then the loading and therefore the compilation are not performed at all. Otherwise, the file is loaded into memory and an attempt is made to compile it. do() does unconditional loading -- no lookup in the %INC hash is made.

If the file is successfully loaded and compiled, then a new key-value pair is added to %INC. The key is the name of the file or module as it was passed to the one of the three functions we have just mentioned. If it was found in any of the @INC directories except ".", then the value is the full path to it in the file system.

The following examples will make it easier to understand the logic.

First, let's see what are the contents of @INC on my system:


% perl -e 'print join "\n", @INC'
/usr/lib/perl5/5.00503/i386-linux
/usr/lib/perl5/5.00503
/usr/lib/perl5/site_perl/5.005/i386-linux
/usr/lib/perl5/site_perl/5.005
.

Notice that . (current directory) is the last directory in the list.

Now let's load the module strict.pm and see the contents of %INC:


% perl -e 'use strict; print map {"$_ => $INC{$_}\n"} keys %INC'

strict.pm => /usr/lib/perl5/5.00503/strict.pm
Since strict.pm was found in /usr/lib/perl5/5.00503/ directory and /usr/lib/perl5/5.00503/ is a part of @INC, %INC includes the full path as the value for the key strict.pm

Tuesday, 11 May 2010

eval

eval() has two forms. The first takes a string, and treats it as Perl
code. It compiles and executes it, returning whatever value is
appropriate. If there is a fatal error, it sets the $@ variable.

my $string = "make the vowels capitals";
my $from = "aeiou";
my $to = "AEIOU";

eval "\$string =~ tr/$from/$to/";
# now $string is mAkE thE vOwEls cApItAls

We had to use eval() here, because tr/// doesn't interpolate variables.
If we'd just done

$string =~ tr/$from/$to/;

we'd be changing $ to $, f to t, r to o, o to o, and m to o, and the
string would be "oake the vowels capitals".

The other form is eval { CODE }. This executes a block of code in a
fail-safe environment. If there are any fatal errors, the $@ is set, and
the block is exited. A common use for this is:

print "Give me a number: ";
chomp(my $n = <STDIN>);
my $result = eval { 100 / $n };
if ($@) { print "You tried dividing by zero.\n" }

Basically, if we didn't use eval { } here, the program would die if the
user entered the number 0.

Wednesday, 24 February 2010

getopts standard in perl

sample getopts usage:


use Getopt::Std;
my $getopts_status = getopts('p:dl:L:tcas');

if (! $getopts_status ||
! (defined($Getopt::Std::opt_p)) ||
! (defined($Getopt::Std::opt_l))) {
die "usage: myscript.pl -p dirname -l logfile [ -L optional logfile ] [-t] [-c] [-a] [-d] [-s]\n";
}



Sunday, 15 November 2009

Chop and Chomp

chop function :

$number = <STDIN>;
chop ($number);
$result = $number + 1;

This is what is happening: When $number is assigned a line of standard input, it really is being assigned a string. For instance, if you enter 22, $number is assigned the string 22\n (the \n represents the newline character). The chop function removes the \n, leaving the string 22, and this string is converted to the number 22 in the arithmetic expression.


chomp function : chomp VARIABLE or chomp LIST

This safer version of "chop" removes any trailing string that corresponds to the current value of $/ (also known as $INPUT_RECORD_SEPARATOR.It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode ("$/ = """), it removes all trailing newlines from the string. When in slurp mode ("$/ = undef") or fixed-length record mode ($/ is a reference to an integer or the like, see perlvar) chomp() won't remove anything. If VARIABLE is omitted, it chomps $_. Example:

while (<>)
{
chomp; # avoid \n on last field
@array = split(/:/);
# ...
}

If VARIABLE is a hash, it chomps the hash's values, but not its keys.You can actually chomp anything that's an lvalue, including an assignment:

chomp($cwd = `pwd`);
chomp($answer = <STDIN>);

If you chomp a list, each element is chomped, and the total number of characters removed is returned.If the "encoding" pragma is in scope then the lengths returned are calculated from the length of $/ in Unicode characters, which is not always the same as the length of $/ in the native encoding.

Note that parentheses are necessary when you're chomping anything that is not a simple variable. This is because "chomp $cwd = `pwd`;" is interpreted as "(chomp $cwd) = `pwd`;", rather than as "chomp( $cwd = `pwd` )" which you might expect. Similarly, "chomp $a, $b" is interpreted as "chomp($a), $b" rather than as "chomp($a, $b)".


For further info: go to unix prompt and type perldoc -f <ANY FUNCTION>

Monday, 9 November 2009

timegm() and gmtime()

timegm() is available perl default module Time::Local for converting readable time to its UTC timestamp.

usage:

$epochtime = timegm($sec,$min,$hour,$day,$mon-1,$year-1900)

timegm expects a list of seconds,minutes,hour,day,mon(0..11),year(YYYY) and returns its epochtime

gmtime() does the opposite way:

usage:
($sec,$min,$hour,$day,$mon,$year) = gmtime(1257811200)

returns todays time in a list. $mon will have month from 0 to 11, $year will have 109 (2009-1900). So, $mon+1 will be right month, $year + 1900 will be the current year

Thursday, 5 November 2009

unless and until

These two are always confusing for me to remember, yet i found a way of remembering the difference between them.

Example :

$line = undef;
unless($line) { print "will enter here" }
unless means if $line is undefined, then enter the loop.Similary we can use this to build a the hash key value pairs as follows.

Below code says for each word, unless the hash key is defined enter inside.This is used for taking repeated words only once of a line.
foreach (@words)
{
unless( exists $hash{$_} )
{
push @uniq,$_ ; #gets word only once
}
}

Notes:

%hash has keys as the words and @uniq array will contains uniq words only.

"exists" is hash function to see if a value exists for a key.

Difference between until and unless :
until says : if condition is true or exists, then don't enter .
unless says : if condition is not true or not exists, then enter.

split()

split is another handy function in perl to split lines into list of space seperated words by default.We can use any delimiter to split any part of line.

For example:
while( my $line = <fh> )  

{
        chomp($line);
        $line =~ s/^\s+//;    # trim leading space               
        $line =~ s/\s+$//;    # trim trailing space
        $line =~ s/^\s+$//;   # trim blank lines
        next unless($line);   # if line is undef skip it
        next if ($line =~ /^#/);  #ignore comment lines
        @Iline = split(/[=&]/,$line,3); #printing the first three matching fields of the line      
        print "@Iline \n"; 

}

rand()

How to generate a random string and append to filenames you want to generate and make them unique.


my $randstring = &gen_rand($randlength);
sub gen_rand()
{

my @chars = ('a'..'z','A'..'Z','0'..'9','_');
my $randstring;
my $length_rand = shift;

foreach (0..$length_rand)
{
$randstring .= $chars[rand @chars];
}
return $randstring;

}

Tweets by @sriramperumalla