السبت، فبراير ٢١، ٢٠٠٩

Perl, You don't want to miss! -3-

Lists and arrays in Perl.


That will be my last post about Perl, however Perl doesn't stop here :) ... you may notice I didn't mention the strength of Perl string processing and file handling. It's worth searching for ;)

What about list?
I may have mentioned before that lists could be generated easily this way in Perl:


(1..5)



This is a range list, it's also valid for character types



What about:

(c..10)



This one is valid too! since "c" is interpolated to Zero (0), then it becomes: (0..10)



Lists in general could be written this way:

('Item1', 'Item2', 'Item3')

or

qw(Item1 Item2 Item3) #you may use any delimeters for this method rather than the parens



Indexing the list is much like any other language you know,using square brackets. The two things that might be of interest in Perl:

- Using a floating number to index, will be floored

- Using a negative number will index starting from the end of the list (backward)

- You may user a list of indexes! this will return another list for the indexed positions (list slice)

- You may combine slicing and ranging to construct the list of indexes. [1,2,3 .. 7]



Assignable lists:

($firstItem , $secondItem) = (1,2);

print $firstItem; #This should print '1'



Array type:

@arrayName = (1,2,3,4);

print @array,"\n"; #Output: 1234

print "@array\n"; #Output: 1 2 3 4 #Notice the spaces! Amazing



Indexing an array variabe:

use "$" to tell Perl what you "want" to get out of the variable.

$firstItem = $arrayName[0]; #Notice the usage of the '$' when indexing the array

#That's because it's returning a single/scalar value;



The "scalar" function may take care of this too.



What's the array's last index? $#

So for example, for array "@arr", that last element's index is: $#arr



List methods:

- shift: Add element to the front

- unshift: Get & remove element from the front

- push: Add element to the back

- pop: Get & remove element from the back

- sort: returns a sorted array, be default it sorts using the string comparison methods.



sort { <:method expression>} @arrayName



So it would be for example:

sort { -($a <=> $b) } @array;

This will return a sorted array, in descending order.

ليست هناك تعليقات: