in reply to lexical scope in if/elsif tests
IMO it is cleaner to use $1 & $2:
my (%foos, %bars); while( my $line = <DATA> ) { chomp $line; if ( $line =~ /^foo ([^:]*):([^:]*)$/ ) { push( @{ $foos{ $1 } }, $2 ); } elsif ( $line =~ /^bar ([^:]*):([^:]*)$/ ) { push( @{ $bars{ $1 } }, $2 ); } else { # warn qq( "$line" is the wrong format.\n ); } }
Or named captures if you're using 5.10:
my (%foos, %bars); while( my $line = <DATA> ) { chomp $line; if ( line =~ /^foo (?<KEY>[^:]*):(?<VAL>[^:]*)$/ ) { push( @{ $foos{ $+{KEY} } }, $+{VAL} ); } elsif ( $line =~ /^bar (?<KEY>[^:]*):(?<VAL>[^:]*)$/ ) { push( @{ $bars{ $+{KEY} } }, $+{VAL} ); } else { # warn qq( "$line" is the wrong format.\n ); } }
|
|---|