Forum Moderators: coopster & phranque

Message Too Old, No Replies

deleting strings from an array

         

mrjcfreak

9:01 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



I have an array, some of whose values are words, some of whose values are just whitespace. What is the best way for 3 lines of code to delete altogether the values which contain just whitespace?

I am willing and eager to use reg exp's.

flashfan

9:28 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



@yourArray = grep /[^\s+]/, @yourArray;

mrjcfreak

9:55 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



Thanks very much... and just one more question...
If I am using a foreach loop, is there a way of using an elements position in an array; e.g.

foreach (@myArray) {
print qq~$_ is in the $nth position in this array~;
}

replacing $nth with the position number.

@myArray = ("apple","banana","carrot");
foreach (@myArray) {
print qq~$_ is in the $nth position in this array\n~;
}

would print:
apple is in the 0 position in ths array
banana is in the 1 position in this array
carrot is in the 2 position int this array

coopster

11:21 pm on Mar 16, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could use a counter:
my $count = 0; 
foreach (@myArray) {
print "$_ is in the " . $count++ . " position in this array\n";
}