Replace Perl array strings with numbers

Associate
Joined
12 Oct 2005
Posts
1,511
Location
Surrey
I have an array which is built up dynamically from a csv file.
There are multiple lines in the csv file, so for each time my script runs through the line on the csv file the array differs.

For each array, I want to replace each variable with a number starting from 1

Example:

@client_list has 3 strings in it. I want to replace each string with 1,2,3 respectively. @client_list differs dependant on which line of the CSV file it is built from, so i will never know how many strings there are in an array.

Any ideas? essentially I guess i want to do something like:

foreach (@client_list) {
$_ = (??number??)
}
 
So you have a one dimensional array with x elements in it, and you are treating each element as a string (there being no variable type in perl). And you want to change each element, to the numeral of its index plus one?

If this is the case, I'd like to see the program and suggest a better way to do what you are doing, but this would work:

Code:
my $index = 0;
foreach my $element (@client_list) {
  $client_list[$index] = $index + 1;
  $index++;
}
Which is a longer, less efficient version of the above, with less perl stunt piloting.
 
Last edited:
Back
Top Bottom