1

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

3
  • 1
    Missing parts of your question: What you have tried, sample input, actual and expected output. Commented Mar 15, 2013 at 13:54
  • What is element.2? Have you got out of step with your indices? Commented Mar 15, 2013 at 14:03
  • 1
    Surely the number of cities is the number of fields in the record minus 3? Commented Mar 15, 2013 at 14:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.