Reputation: 11
I have a file that I am reading in. I'm using perl to reformat the date. It is a comma seperated file. In one of the files, I know that element.0 is a zipcode and element.1 is a counter. Each row can have 1-n number of cities. I need to know the number of elements from element.3 to the end of the line so that I can reformat them properly. I was wanting to use a foreach loop starting at element.3 to format the other elements into a single string.
Any help would be appreciated. Basically I am trying to read in a csv file and create a cpp file that can then be compiled on another platform as a plug-in for that platform.
Best Regards Michael Gould
Upvotes: 1
Views: 812
Reputation: 9959
Well if your line is being read into an array, you can get the number of elements in the array by evaluating it in scalar context, for example
my $elems = @line;
or to be really sure
my $elems = scalar(@line);
Although in that case the scalar
is redundant, it's handy for forcing scalar context where it would otherwise be list context. You can also find the index of the last element of the array with $#line
.
After that, if you want to get everything from element 3 onwards you can use an array slice:
my @threeonwards = @line[3 .. $#line];
Upvotes: 1
Reputation:
you can do something like this to get the fields from a line:
my @fields = split /,/, $line;
To access all elements from 3 to the end, do this:
foreach my $city (@fields[3..$#fields])
{
#do stuff
}
(Note, based on your question I assume you are using zero-based indexing. Thus "element 3" is the 4th element).
Alternatively, consider Text::CSV
to read your CSV file, especially if you have things like escaped delimiters.
Upvotes: 2