Re: creating hash from scalar variable



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>) {

## 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) );

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

## 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.

Hope this helps!

-m
.



Relevant Pages

  • Re: creating hash from scalar variable
    ... Timestamp = 1177282824'; ... Reading a file line by line is a fairly recognizable pattern to perl programmers of all levels, so it may assist future maintainers. ...
    (perl.beginners)
  • Re: Formatting tracing?
    ... (This with a filehandle pointing at a pipe, I was going to try a tied ... I'd like the timestamp and pid to be ... included in the trace. ... things can go wrong with named pipes, which could cause me to hang. ...
    (perl.dbi.users)