파라미터 패싱에 대한 좋은 펄 코드가 있어서 소개한다.

 

 

출처 :

 

http://www.cs.cf.ac.uk/Dave/PERL/node61.html

Passing Parameters to Functions

When we introduced Functions we talked about passing parameters to functions. At the time, we were not able to pass more than one array to a function. This was because functions only see one array (the @_ array) when looking for parameters. References can be used to overcome this limitation.

Let's start off by passing two arrays into a function to show that the function only sees one array (pass_par.pl):

firstSub( (1..5), ("A".."E"));



sub firstSub {

    my(@firstArray, @secondArray) = @_ ;



    print("The first array is  @firstArray.\n");

    print("The second array is @secondArray.\n");

}

This program displays:

The first array is  1 2 3 4 5 A B C D E.

The second array is .

Inside the firstSub() function, the @firstArray variable was assigned the entire parameter array, leaving nothing for the @secondArray variable. By passing references to @arrayOne and @arrayTwo, we can preserve the arrays for use inside the function. Very few changes are needed to enable the above example to use references (pass_ref.pl):

@array1  = (1..5);
@array2  = ("A".."E");

firstSub( \@array1,  \@array2);         # One



sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_;   # Two



    print("The first array is  @{$ref_firstArray}.\n");  # Three

    print("The second array is @{$ref_secondArray}.\n"); # Three

}

This program displays:

The first array is  1 2 3 4 5.

The second array is A B C D E.

Three things were done to make this example use references:

1.
In the line marked "One," backslashes were added to indicate that a reference to the array should be passed.
2.
In the line marked "Two," the references were taken from the parameter array and assigned to scalar variables.
3.
In the lines marked "Three," the scalar values were dereferenced. Dereferencing means that Perl will use the reference as if it were a normal data type-in this case, an array variable.

An alternative more modern way of achieving the same as above is to create a Perl Reference array using square brackets:

firstSub( [1..5], ["A".."E"] );


sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_;    # Two



    print("The first array is  @{$ref_firstArray}.\n");  # Three

    print("The second array is @{$ref_secondArray}.\n"); # Three

}

'perl' 카테고리의 다른 글

Array 다루기 #2  (0) 2008.06.05
Array 다루기 #1  (0) 2008.06.05
Passing Parameters to Functions  (0) 2008.06.05
Perl의 String 관련 함수  (0) 2008.03.22
bash는 float 변수 연산이 안된다.  (0) 2007.10.21
펄 해쉬 이야기 #2  (0) 2007.10.19
Posted by 김용환 '김용환'

댓글을 달아 주세요