-------- Original Message --------
Subject: Re: Building/defining variables from an value in string
Date: Wed, 23 Apr 2008 04:46:21 -0400
From: Uri Guttman <[EMAIL PROTECTED]>
To: [EMAIL PROTECTED]
Newsgroups: perl.beginners
References: <[EMAIL PROTECTED]> <[EMAIL PROTECTED]> <[EMAIL PROTECTED]>

The following message is a courtesy copy of an article
that has been posted to perl.beginners as well.

"AG" == Aruna Goke <[EMAIL PROTECTED]> writes:

  AG> my $string = "field1,int,10#field2,string,abc#field3,varchar,abc123";
  AG> my @vals = split(/#/,$string);

  AG> my %h;
  AG> my @arr;

  AG> for (@vals){
  AG> @arr = (split/,/)[0,2];
  AG> %h = (@arr);

simple one liner (untested) (assumes clean data with no # or , in it):

my %hash = $string =~ /(\w+),\w+,(\w+)/g ;

using a regex to parse out all the key/value pairs is simpler and much
much faster than all those splits and loops. and only 1 (the final)
variable needs to be declared.

uri

--
Uri Guttman ------ [EMAIL PROTECTED] -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Free Perl Training --- http://perlhunter.com/college.html --------- --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------


my %hash = $string =~ /(\w+),\w+,(\w+)/g ;

for (keys %hash){
say $_ ,' -- ', $hash{$_};
}

goksie



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to