Referencing Perl

This blog is created to share perl resources all round the world and to explore the same.

Name:
Location: Chennai, TamilNadu, India

A Computer Freak, interested in programming open source

Thursday, November 17, 2005

string common to 2 strings



The solution



sub common {
if ( $_[0] eq $_[1] ) {
return( $_[0], "", "" );
} else {
use bytes;
my ( $pos, $len0, $len1 ) = ( 0, length($_[0]), length($_[1]) );
# find the offset of the first byte that differs
while ( vec($_[0], $pos, 8) == vec($_[1], $pos, 8) ) {
$pos++;
last unless ( $pos < $len0 && $pos < $len1 ); }

return( unpack("a${pos}", $_[0]),
unpack("x${pos}a*", $_[0]),
unpack("x${pos}a*", $_[1]), ); } }


Another Solution is



sub common {
my ($a,$b)=@_;
my ($long,$short);
if (length ($a) <= length ($b))
{
($long,$short) = ($b,$a); }
else {
($long,$short) = ($a,$b); }
my $i=0;
my $common="";
while ($i < str =" substr($short,$i,1);"
t="$i;"
long="~/$str/);" long="~/$str/)"
uni =" substr($short,$t,1));" long="~m/$str$uni/);" common =" $str">



--Prasanna.K


Changing the position of element in a array

Trying to find the position of an element in an array and then moving that element to the last position in the array.i.e the last element will then become the second last.


The Solution is ....



for( $i = 0; $i < @array; $i++){
if( $array[$i] == $look ) {
@out = (@array[0..($i-1)], @array[($i+1)..scalar(@array)], $array[$i]);
last;
} }

--Prasanna.K

Tuesday, April 12, 2005

A useful link with Heap of Perl Resources


--prasanna.k

Wednesday, March 30, 2005

Removing List of things from list of things

my @list = qw/1 2 3/;
%temp=();
my @stoplist = qw/1 2/;
@temp{@list} = ();
delete @temp{@stoplist};
print keys %temp;
--prasanna.k

Swapping of two number without any temporary variables

$a =1;
$b =2;
$b ^= $a ^= $b ^= $a;
print "a = $a, b = $b\n";
--prasanna.k

Removing Duplicates from Array


my @array = qw/1 2 3 4 1 2 3 4/;
%temp = ();
map{$temp{$_}++}@array;
for (sort keys %temp) {
print "$_=>$temp{$_}"."\n";
}
--prasanna.k