http://qs321.pair.com?node_id=644004

cidaris has asked for the wisdom of the Perl Monks concerning the following question:

I use an application called Easy-IP to keep track of IP utilization. Underneath lies a Firebird database, which I've extracted to CSV. The header line lists all the columns, but I wanted to know the array index for processing. Short of counting commas, I came up with:
head -1 ./current.csv |perl -ane '$i = 0; s/\,/" ".$i++."\n"/eg; print +;'
The header line looks like so:
SUBNET_ID,AUTONOMOUS_NETWORK_ID,PARENT_ID,TREE_PATH,SUBNET,CIDR_MASK,I +P_VERSION,LOW_ADDRESS,HIGH_ADDRESS,BROADCAST_ADDRESS,SHORT_SUBNET,ASS +IGNED_ADDRESSES,CHILD_SUBNET_COUNT,COMMENT,SYSTEM_FLAG1,REPLICATED_FR +OM,CREATED,UPDATED,LOCATION,USAGE,NETWORK_NAME,IP_NETWORK,IP_NETWORK_ +BLOCK,ORGANIZATION,ADMIN_CONTACT,TECH_CONTACT,ORG_NAME,STREET_ADDRESS +,CITY,STATE,POSTAL_CODE,COUNTRY_CODE,PRIMARY_SERVER,SECONDARY_SERVER

My output, abbreviated:
SUBNET_ID 0 AUTONOMOUS_NETWORK_ID 1 PARENT_ID 2 TREE_PATH 3 SUBNET 4 ...
I bet the brains at PM can do better. Suggestions?

Replies are listed 'Best First'.
Re: enumerate column numbers
by BrowserUk (Patriarch) on Oct 10, 2007 at 16:11 UTC

    See perlrun for -F

    C:\test>perl -aF, -nle"}{print $_,' ', $i++ for @F" junk.txt SUBNET_ID 0 AUTONOMOUS_NETWORK_ID 1 PARENT_ID 2 TREE_PATH 3 SUBNET 4 CIDR_MASK 5 IP_VERSION 6 LOW_ADDRESS 7 HIGH_ADDRESS 8 BROADCAST_ADDRESS 9 SHORT_SUBNET 10 ASSIGNED_ADDRESSES 11 CHILD_SUBNET_COUNT 12 COMMENT 13 SYSTEM_FLAG1 14 REPLICATED_FROM 15 CREATED 16 UPDATED 17 LOCATION 18 USAGE 19 NETWORK_NAME 20

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: enumerate column numbers
by mwah (Hermit) on Oct 10, 2007 at 16:06 UTC
    Let Perl do the array handling,
    head -1 ./current.csv | perl -054 -ane 'chomp and print "$_ ".$c++."\ +n" for@F'
    Regards

    mwa
Re: enumerate column numbers
by Fletch (Bishop) on Oct 10, 2007 at 16:43 UTC

    You might also want to take a gander at Tie::Handle::CSV which gives you back a tied hash which lets you access (and modify) fields by name. It's not Ruport, but it's handy. :)

Re: enumerate column numbers
by cidaris (Friar) on Oct 10, 2007 at 16:32 UTC
    I can't believe I overlooked setting the record separator. You guys win.