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