in reply to Convert a Tab-Delimeted File to XML

#!/usr/bin/perl use XML::Simple; my @file; my (@labels) = split /\s+/, <DATA>; while (<DATA>) { chomp; my %line; @line{@labels} = split /\t/; push @file, \%line; } print XMLout(\@file); __DATA__ First Last Fred Flintstone Barney Rubble Betty Rubble Wilma Flintstone
generates
<opt> <anon First="Fred" Last="Flintstone" /> <anon First="Barney" Last="Rubble" /> <anon First="Betty" Last="Rubble" /> <anon First="Wilma" Last="Flintstone" /> </opt>
Season to taste.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Convert a Tab-Delimeted File to XML
by tstock (Curate) on Sep 30, 2001 at 05:26 UTC
    I hate to point out something in Randalls code, but shouldn't the first split be on tabs and not on one or more spaces ? a label "First Name" could exist.
      Good point - personally, i hate tab-delimited files. If my labels can contain whitespace, then i will use something like a colon or a semi-colon or maby even -=:TOMMY_LEE:=-

      i think merlyn chose \s+ to take care of situations where tabs and spaces could be inter-mixed.

      it all boils down to TIMTOWTDI ;)

      jeffa

        My comment would have broken merlyns code and I feel I should post an apology. A split on \t would have left @values with an extra linefeed, so to be able to handle a proper tab-separated header you also need to:
        chomp $labels[-1]
        after splitting on \t. If the header is really one-or-more-whitespace-characters-separated, then the original code is fine. Feel free to mod me down or take experience points or whatever is the punishment du jour :-)
        Naw man... *NIKKI SIXX* is a much better delimiter.

        /\/\averick