Re: creating hash from scalar variable



Unf. Got the picture! I'll spend my night in the stockades :)

-m

Rob Dixon wrote:
Matthew J. Avitable wrote:

Given the original string ...
my $test =
'NAS-IP-Address = 192.168.42.1
.......
Acct-Unique-Session-Id = "87d380e1881d226c"
Timestamp = 1177282824';


You could also invoke perl 5.8's ability to treat an in-memory string as a file:

## get a filehandle on $test
open(my $fh, '<', \$test) or die "Unable to open scalar ref for reading: $!";

while (my $line = <$fh>) {

Hmm. I don't feel this is an improvement over just

foreach (split /\n/, $line) {
:
}

or even

while ($test =~ /(.*\n?)/g) {
my $line = $1;
:
}

to avoid duplicating the whole string at once.

## split on '=' with a max of two resulting fields, clear spaces adjacent to '='.
## clear newlines as well.
chomp ( my ($k, $v) = split(/\s*=\s*/, $line, 2) );

Why chomp here? You're chomping $k, which /can't/ end in a record, as well as $v.
Just

chomp $line;
my ($k, $v) = split /\s*=\s*/, $line, 2;

is more appropriate.


## clear out the quotes in the value
$v =~ s/"//og;

Why use the /o modifier when there are no variables being interpolated into
the regex?

Even better (in terms of speed) would be

$v =~ tr/"//d;

although I admit I tend to use s/// exclusively myself.

Also why remove the quotes when the OP didn't say he wanted to, and may actually
need them?

## do something with your key and value:
print "Key is $k, Value is: $v\n";

}

close $fh;


Reading a file line by line is a fairly recognizable pattern to perl programmers of all levels, so it may assist future maintainers.

...unless it stops working, when opening a string on a filehandle is a
fairly /unrecognisable/ pattern, and the maintainer may be stumped!

Cheers,

Rob



--
+ Matt J. Avitable: Senior Systems Analyst, Richweb, Inc.
+ Richweb.com: Providing Internet-Based Business Solutions since 1995
+ (804) 747.8592 x 109

.