User Tools

Site Tools


ower_own_perl_wiki

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
ower_own_perl_wiki [2008/01/31 21:29] – typo fix cs243050ower_own_perl_wiki [2008/09/29 03:02] (current) cs243081
Line 53: Line 53:
 | LOCK_UN      | unlocks the previously locked file    |  | LOCK_UN      | unlocks the previously locked file    | 
 | LOCK_NB      | should be bitwise 'or'-ed with either LOCK_SH or LOCK_EX and will result in a non-blocking lock    |  | LOCK_NB      | should be bitwise 'or'-ed with either LOCK_SH or LOCK_EX and will result in a non-blocking lock    | 
 +\\ 
 +----
  
 +===== Array manipulation: Removing duplicate array items =====
 +
 +So by now we know what an array looks like and maybe we've learned a few  ways to manipulate it.  Well, here's a trick to remove duplicate items in an array while preserving the item's order by using a hash.
 +
 +Here's a couple of things you ought to know to fully understand the code:
 +
 +  * A hash is like an arrays except that they link a key to a value and the key is unique.
 +  * $_ is a special perl variable known as the default or implicit variable.  In our example below it'd be the implicit value of the current @array1 item. 
 +
 +<code perl>
 +@array1 = qw(one two one three four two);
 +
 +foreach (@array1) {
 +    push(@array2, $_) unless ($seen{$_}++);
 +}
 +
 +print "@array2";
 +</code>
 +
 +**output:** one two three four
 +
 +The reason that we're using a hash here is to use its limitation (each key must be unique) to our advantage.  In this example we use a hash called "seen" with keys set to each item in our array. For each string we test to see if that key already refers to a non-false value. The post-increment operator (++) adds one to that key's value, but only after the condition is checked. The result is that the first time a key string is encountered the condition is false (since the value is undefined) and the key is therefore pushed onto our second array. The key is then incremented and any further test of the key's value will evaluate "true" (i.e. non-zero, and non-empty).
 +
 +__Reference:__ http://www.perlcircus.org/arrays.shtml
ower_own_perl_wiki.1201814975.txt.gz · Last modified: 2008/01/31 21:29 by cs243050

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki