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