Wednesday, February 15, 2012

Friday, December 2, 2011

Perl - [ Function Splice / Array ]


#!/usr/bin/perl
use strict;
use warnings;

my @array = ( 1..20 );
my @array2 = ( 1000..1005 );
print "\@array : @array\n\@array2 : @array2\n";
my @rmArray = splice ( @array, 5, scalar(@array2), @array2 );
print "After spliece\n";
print "\@array : @array\n\@rmArray : @rmArray\n";

Result :
$ perl splice.pl 
@array : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
@array2 : 1000 1001 1002 1003 1004 1005
After spliece
@array : 1 2 3 4 5 1000 1001 1002 1003 1004 1005 12 13 14 15 16 17 18 19 20
@rmArray : 6 7 8 9 10 11

perl -e ' @an = ('a','b','c'); splice(@an,1,1); print "@an\n";
a c
andre@T3500:~> perl -e ' @an = ('a','b','c','d','e'); splice(@an,3,1); print "@an\n";   '
a b c e
andre@T3500:~> perl -e ' @an = ('a','b','c','d','e'); splice(@an,2,2); print "@an\n";   '
a b e
andre@T3500:~>





Syntax: splice (array to be modified, early modification, amount of values ​​to be inseritdo, values ​​to be insert)

Perl - [ $perl -e ' Command Line ' ] - [ Shift / Unshift / Pop / Push ]


Note: Open shell and type the code "command line" below!
Syntax : $ perl -e ' command line '

1) Profile example 

$ perl -e '@array = (1..5); print "Result : @array \n";'
Result : 1 2 3 4 5 


2) Removes the first element of the array
$ perl -e '@array = (1..5); shift (@array);print "Result : @array \n";'
Result : 2 3 4 5 


3) Remove the last element of the array
$ perl -e '@array = (1..5); pop (@array);print "Result : @array \n";'
Result : 1 2 3 4 

4) Insert the last element of the array
$ perl -e '@array = (1..5); push (@array,"command line");print "Result : @array \n";'
Result : 1 2 3 4 5 command line 

5) Insert at the beginning of the array
$ perl -e '@array = (1..5); unshift (@array,"command line");print "Result : @array \n";'
Result : command line 1 2 3 4 5


Note: Always use push and pop instead of shit and unshift when possible, for push and pop are more efficient with large array

Wednesday, November 30, 2011

Sunday, November 13, 2011

Perl - [ Seconds To Hours ]

 #!/usr/bin/perl
use strict;
use warnings;

my $seconds = shift or die "Entre the seconds parameter\n";
my @parts = gmtime($seconds);
printf ("day -%4d\t hours - %4d\tminute - %4d\tseconds - %4d\n",@parts[7,2,1,0]);


$perl secondsTohours.pl 89600
day -   1        hours -    0   minute -   53   seconds -   20
$perl secondsTohours.pl 3600
day -   0        hours -    1   minute -    0   seconds -    0

Perl - [ Second TO Hours [Sub] ]


#!usr/bin/perl
use strict;
use warnings;

my $value = shift or die "Enter the second parameter\n";

&secondTOhours(\$value);

sub secondTOhours(){
 
    my ($seconds)= @_;

    my $hrs = int( $$seconds / (60*60) );

    my $min = int( ($$seconds - $hrs*60*60) / (60) );

    my $sec = int( $$seconds - ($hrs*60*60) - ($min*60) );

    print("$hrs hours, $min minutes, and $sec seconds.\n");
}


$perl secondsTohours.pl 3600

1 hours, 0 minutes, and 0 seconds.