Perl Learning Note - Column Swap Function

Suppose we want to have a function to deal with a global matrix (@matrix) to do column swap, then we can declare the function as following :
sub ColSwap
{
    my($Idx1,$Idx2) = @_;  # Idx1 and Idx2 are global variable
    my($idx, $Tmp0);       # idx and Tmp0 are local variable , only exist in this function
    for($idx = 0; $idx < $max_col; $idx++)
    {
           $Tmp0 = $matrix[$Idx1*$max_col + $idx];
           $matrix[$Idx1*$max_col + $idx] = $matrix[$Idx2*$max_col + $idx];
           $matrix[$Idx2*$max_col + $idx] = $Tmp0;
    }
}
NOTE : matrix and max_col are global variable , we don't need to give any input argument to ColSwap. We can use this kind of function using 
&ColSwap(Column#1 , Column#2);

We can return value like we program in C , for example :

sub ColSwap
{
    my($Idx1,$Idx2) = @_;  # Idx1 and Idx2 are global variable
    my($idx, $Tmp0);       # idx and Tmp0 are local variable , only exist in this function
    for($idx = 0; $idx < $max_col; $idx++)
    {
           $Tmp0 = $matrix[$Idx1*$max_col + $idx];
           $matrix[$Idx1*$max_col + $idx] = $matrix[$Idx2*$max_col + $idx];
           $matrix[$Idx2*$max_col + $idx] = $Tmp0;
    }
    return ($idx , $Tmp0)    # We return the value of idx and Tmp0
}
And finally if we want to get the value of function returns, we can simply using the following script : 
@Tmp1 = &ColSwap(Column#1, Column#2);

NOTE : Local variable usually need an initial value, otherwise sometimes will have uninitialize error.


留言

這個網誌中的熱門文章

Spread Spectrum Clock Generation (SSCG)

SIFS/DIFS/PIFS (802.11 Mac Layer)