in reply to Help:getting parts of the strings from a file into managable variables

Your data looks a little suspect (lacking a few /, and inconsistent case), but this parses it and builds a nested hash from it.
my $user; my %uservariables; while(<DATA>){ chomp; my ($key, $value) = m{^<([^>]+)>(.*)<}i or die $_; $key = lc $key; #to adjust for case differences if ($key eq "userid"){ $user = $value; next; } $uservariables{$user}->{$key}=$value; } use Data::Dumper; print Dumper(\%uservariables); __DATA__ <UserID>46786<UserID> <start>2004-10-21TO09:57:25Z</start> <dev>Some Text</dev> <var1>some string</var1> <var2>some string</var2> <USerID>57864</UserID> <start>2004-10-25TO09:57:25Z</start> <dev>Some Text</dev> <var1>some string</var1> <UserID>46786<UserID> <var3>some string</var3> <var4>some string</var4> <UserID>98766</UserID> <start>2004-10-21TO09:57:25Z</start> <dev>Some Text</dev> <var1>some string</var1> <var2>some string</var2> <var5>some string</var5> <var6>some string</var6> <USerID>57864</UserID> <var4>some string</var4> <var6>some string</var6>
  • Comment on Re: getting parts of the strings from a file into managable variables
  • Download Code

Replies are listed 'Best First'.
Re^2: getting parts of the strings from a file into managable variables
by my_perl (Initiate) on Nov 12, 2004 at 18:01 UTC
    Hi, thanks a lot for response, it is working great. What do i need to change if i have spaces before strings, and number of spaces is not constant? Thanks again :) Aida
      Hmmm, you might try changing the regexp to something like
      my ($key, $value) = m{^\s*<([^>]+)>\s*(.*)<}i;
      Although I'm starting to agree with the others that a real XML parser might be the way to go.
Re^2: getting parts of the strings from a file into managable variables
by my_perl (Initiate) on Nov 19, 2004 at 17:42 UTC
    Hi, how would i access these variables?
    foreach userid i would like to print only var1 , its value, and var2 , its value.
    foreach $key (keys %uservariables) {
    ???????
    }
    THanks
      Something like
      for my $key (keys %uservariables){ print "User $key has var1: $uservariables{$key}->{var1}, var2: $user +variables{$key}->{var2}"; }
        Thanks a bunch
        what if var2, var3 shows up few times for single userID
        and i would like just first occurence of var2 and last
        occurence of var3.
        Thanks :)