Sumit Shah wrote:
>
> Rob Dixon wrote:
>>
>>> Sumit Shah wrote:
>>>
>>> I have a string like: 'a = 1; b = 2; c = 3; d = 4'
>>>
>>> Whats the best way to parse it so that I can get a value for c, which is
>>> 3? I have used the hash approach. But, I was wondering if there is a
>>> faster way to do it in Perl.
>>
>> What do you mean by 'the hash approach'? Can you post some code that you've
>> written so that we can better understand what it is you're trying to do? It
>> would also be nice to see some of the actual data you need to process, as I
>> assume what you've shown is a simplification (otherwise all you would need
>> to write is $c_value = 3).
>
> I am doing the following:
>
> my $cookie = $r->headers_in->{'Cookie'};
> my @cookieArray = split(/\;\s/,$cookie);
> my %hashMap;
> my $cookieItem;
> foreach $cookieItem (@cookieArray){
>   my @subArray = split("=",$cookieItem);
>   my $key = $subArray[0];
>   my $value = $subArray[1];
>   $hashMap{$key}=$value;
> }
>
> my $userid;
> if (exists($hashMap{'USERID'})) {
>   $userid=$hashMap{'USERID'};
> }
> else {
>   return OK;
> }
>
> I was just wondering if I can do something much quicker than this. I
> need to use it inside Apache and need it to be as lightweight as possible.

(Please bottom-post your replies so as to keep long threads legible. Thanks.)

I wouldn't worry about the speed of something as simple as this, but you can
write it a lot more simply, depending on how much of the HTTP cookies
specification (RFC2109) you want to support. As it stands, your code doesn't
allow for spaces around the equals sign, although you have put them in your
sample data. As long as there are never space characters embedded in the value
field, you can derive your hash by writing:

my %hashMap = $cookie =~ /[^=;\s]/g;

which simply fills the hash with all contiguous sequences of characters that
don't contain an equals, semicolon or whitespace. This gives the hash content
that you expect if, as I said, the cookies field is always in the simple form
you have shown. It is also likely to be faster, although I don't believe it
matters.

HTH,

Rob


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


Reply via email to