-------- Original Message --------
Subject: Re: Building/defining variables from an value in string
Date: Wed, 23 Apr 2008 04:46:21 -0400
From: Uri Guttman <uri@stemsystems.com>
To: myklass@gmail.com
Newsgroups: perl.beginners
References: <671418.60994.qm@web53008.mail.re2.yahoo.com>
<f223dcde0804221452r61c40debg24b7471f327b1a65@mail.gmail.com>
<480ED976.1020108@gmail.com>
The following message is a courtesy copy of an article
that has been posted to perl.beginners as well.
>>>>> "AG" == Aruna Goke <myklass@gmail.com> 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 ------ uri@stemsystems.com --------
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