in reply to array range positions

G'day juanito23,

What you show at the start is invalid syntax. If that's returned from Text::CSV's getline() method, you have an arrayref (["m2000_id", ...]). If it's really an array, it looks like ("m2000_id", ...). Furthermore, as you've said "already done", this would seem to suggest that this is partially processed data: perhaps you started with string of comma-separated values. Not knowing the data you're working with is not a good start.

Your other code fragment is incomplete. Where's the if block? What value does $_ hold? How does it get that value? (By the way, 0 .. 10 is a range of 11 values!)

Here's how I might have iterated over an array testing both element content and array index:

#!/usr/bin/env perl -l use strict; use warnings; my @array = qw{! 1 A @ 2 b $ 3 c % 4 D ^ 5 e}; for my $i (0 .. $#array) { if ($array[$i] =~ /[a-zA-Z]/ || $i < 10) { print "[$i] Quote: '$array[$i]'"; } else { print "[$i] Don't quote: '$array[$i]'"; } }

Output:

[0] Quote: '!' [1] Quote: '1' [2] Quote: 'A' [3] Quote: '@' [4] Quote: '2' [5] Quote: 'b' [6] Quote: '$' [7] Quote: '3' [8] Quote: 'c' [9] Quote: '%' [10] Don't quote: '4' [11] Quote: 'D' [12] Don't quote: '^' [13] Don't quote: '5' [14] Quote: 'e'

That might at least give you a starting point.

-- Ken

Replies are listed 'Best First'.
Re^2: array range positions
by juanito23 (Novice) on Apr 24, 2014 at 08:46 UTC

    Hi, yes sorry for not put all the code here, but the interesting part is on the elsif clause. Anyway, seems the best way to go through is as you advised with a for counter

    Here's the whole if / else cycle i'm using for a better understanding:
    foreach (@csv_out){ if($_ eq ""){ #$_ = 'NULL'; $_ = 'NULL'; print WRITEFILE "$_" . "," ; } elsif ($_ =~ m/[a-zA-Z]/ || ($j<10 && $j>=0)){ print "$_\n"; $_=~ s/,/ /g; print WRITEFILE '"'."$_".'"' . "," ; $j=$j-1; } else { $_=~ s/,/ /g; print WRITEFILE "$_" . "," ; }

    so, the first if is to match any empty field, the elsif will match the fields with characters, and the else will do all the others. Hopefuly your advise sorted the problem.

    Thanks!