Combining split with Other Functions

   



The Perl join Function

The Perl join function is useful when you need to concatenate a set of strings that are stored in an array.

Listing C.19 join1.pl

start example
my($discard1)    = ""; my($discard2)    = ""; my(@numbersArray); my($currentLine) = "mumbo jumbo 1 2 3"; ($discard1, $discard2, @numbersArray) =                                  split(/\s+/, $currentLine); my($secondLine) = join(' ', @numbersArray); print "second line $secondLine\n";
end example

Remarks

You can launch the Perl script join1.pl in Listing C.19 from the command line as follows,

perl -w join1.pl

and the output is as follows:

second line = 1 2 3

The combination of split and join is useful when you need to split a line containing one delimiter and then reconstitute the line with another delimiter. There are other ways to accomplish the same task; for example, if you need to replace a line with a colon (':') delimiter with a pipe symbol ('|'), you could also do something like the following, which does not require the use of either split or join:

$currentLine =~ s/:/\|/g;

Notice the use of a backslash ('\') in order to 'escape' the pipe symbol.

Creating Custom Perl Functions

Listing C.20 displays a simple Perl script that invokes a custom function in order to calculate the sum of two numbers.

Listing C.20 addTwo.pl

start example
my($first) = 3; my($second) = 4; addTwoNumbers(3,4); sub addTwoNumbers($$) {    my($sum) = 0;    my($first, $second) = @_;    $sum = $first + $second;    print "The sum of $first and $second is $sum\n";  }
end example

Remarks

You can launch the Perl script addTwo.pl in Listing C.20 from the command line as follows,

perl -w addTwo.pl

and the output is as follows:

The sum of 3 and 4 is 7

For backward compatibility, functions written in pre-release 5 versions of Perl are invoked with an ampersand ('&') as given below:

&addTwoNumbers(3,4);



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net