For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > August 2005 > Re: Need an explanation









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Need an explanation
John W. Krahn

2005-08-27, 3:55 am

Binish A R wrote:
> I've a file, which has entries like the following ...
>
> IDENTIFIER1=value1;
> IDENTIFIER2=value2;
> IDENTIFIER3=value3;
>
> etc
>
> I've got to parse the above file and am using a hash to do the same ...


Have you thought about using one of the many modules on CPAN that does this
for you?


> Here is my code ...
>
>
> while (<> ) {
> chomp;
> next if /^#/;
> next if /^$/;
> %CONF = split /=/;
> }
>
>
> But %CONF contains only the last key/value pair :-/


That is because the contents of the hash %CONF are being replaced by the
assignment to the hash.


> So I had to modify the above script to
>
> while (<> ) {
> chomp;
> next if /^#/;
> next if /^$/;
> $ref = [ split /=/ ];
> $CONF{$ref->[0]} = $ref->[1];
> }
>
> The above is working fine.


That is because it is the correct way to ADD data to a hash.


> So my question is why isn't the first code working?
> I don't want to use too many variables in my script,
> even with my second script I needed an extra variable viz $ref.


If you make the results from split() local to the while loop using my() then
they will not affect the number of variables outside the while loop.

my ( $key, $value ) = split /=/;
$CONF{ $key } = $value;
}
# End of loop so $key and $value are no longer in scope.


> Is it possible to get the job done using the first script?


No, however you can do it by reading the whole file into a list and processing
that:

my %CONF = map split( /=/ ), grep !/^$/, grep !/^#/, map { chomp; $_ } <>;



P.S. Could you please not send graphics files to the list? TIA


John
--
use Perl;
program
fulfillment
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com