|
Programming Portfolio -
Perl
|
|
Written by Jeremy P. McKay
|
|
Tuesday, 14 July 2009 18:23 |
|
I have an array called @data. I want to check each element in the array for a value, and if that value exist, I wan to delete it
I could try
@data =~ ~ s/$postalCode//;
### creates an error about private arrays
Maybe this
for my $dat(@data){ $dat=~ s/$postalCode//; }
The above code does not modify the array at all. We could create a temporary array and then pop puch and reassign upon going through each element. That could be time consumming especially if I have 250,000 arrays. So let's look at map. Charles Galpin has written a pretty simple tutorial on using map here http://articles.techrepublic.com.com/5100-10878_11-1044685.html.
So after reading Charles' article, I try .
map {s/$postalCode//} @data;
Just to a make sure it works I ran the a line of data through it. You should always check yoru code on small sets of data. The test and results are below.
my $data = "Beijing Normal University Beijing 100875 China";
my @data = split/\t/, $data; $postalCode = 100875; for my $d(@data){ print "$postalCode $d\n";
}
print "Postal Code Removed\n";
map {s/$postalCode// } @data; # just checking for my $d(@data){ print "$postalCode $d\n";
} exit;
100875 Beijing Normal University 100875 Beijing 100875 100875 China Postal Code Removed 100875 Beijing Normal University 100875 Beijing 100875 China
Hope this helps in your data munging
|
|
Last Updated ( Tuesday, 14 July 2009 19:19 )
|