Hi Dennis,
On Wednesday 01 December 2010 11:24:02 Dennis Jakobi wrote:
> Hi there,
>
> I have the following problem:
>
> I want to read a logfile in which every line follows this rule:
> <value1>:<value2>:<value3>...
>
> But the number of values differs. Sometimes a line has 2 values (the
> minimum) and sometimes 3 or more values. Now I want to push these
> values into a hash that follows that form:
> $hash->{value1}->{value2}...
>
> This is what I have so far:
>
First a few comments on your code:
> sub readLog {
> my $self = shift;
> my $logfile = getFilename();
Are you sure you want to:
1. Use camelCase.
2. Not do $self->get_filename().
3. Call it "get_filename()" instead of "get_log_filename()"?
>
> open LOG, "<$logfile";
Use three-args-open, lexical filehandles, etc:
http://perl-begin.org/tutorials/bad-elements/#open-function-style
>
> foreach my $line (<LOG>) {
«while (my $line = <$log>)» would be more preferable here because it will
consume less memory:
http://perl-begin.org/tutorials/bad-elements/#foreach-lines
> my @values = split /\:/, $line;
split /:/ will work just as well, as ":" is not a special character.
> ... # at this point I don't know what to do :(
OK, here's what you can do (untested):
[code]
my $hash_ref = \%hash;
foreach my $val (@values[0 .. $#values-2])
{
$hash_ref = ($hash_ref->{$val} ||= {});
}
$hash_ref->{$values[-2]} = $values[-1];
[/code]
I did not deal with some edge cases, but hopefully it will be OK.
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Funny Anti-Terrorism Story - http://shlom.in/enemy
<rindolf> She's a hot chick. But she smokes.
<go|dfish> She can smoke as long as she's smokin'.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/