http://qs321.pair.com?node_id=932902


in reply to Advice on script

A few minor comments:

  1. For clarity, why not call this 'macaddr' instead of 'chaddr'? (Same for my $chaddr, etc.)
    chaddr => 'XX:XX:XX:XX:XX:XX', # MAC Address of sending interface
  2. sleep 5; # wait for 5..., etc. is obvious. How about:
    sleep 5; # allow capture process to establish sleep 10; # allow capture
  3. In this sequence, you don't need two arrays, and you can simplify a couple things:
    #my @macaddr = split(/:/, $chaddr); my @chaddr = split(/:/, $chaddr); #push(@macaddr, 0) for (1..10); push(@chaddr,(0)x10); #my @chaddr = map { hex($_) } @macaddr; @chaddr = map { hex } @chaddr; # or combined, using the clearer(?) @macaddr: @macaddr = map { hex } (split/:/,'10:FF:2B:40:8C:FE'), (0)x10;
  4. You are modifying $i throughout this loop! In fact, you have a comment (# i = 0) that is certainly untrue the first pass, and may never be true.
    for (my $i = 0; $i <= $#options; $i++) { my $option = hex($options[$i++]); last if ($option == 255); # end of DHCP Options my $length = $options[$i++]; # i = 0 my $offset = hex($length) + $i; for (my $k = $i; $k <= ($offset - 1); $k++ ) { push(@{$opts{$option}}, $options[$k]); } $i = $offset - 1; }
  5. A thought on printing:
    for my $key (keys %opts) { print $key, " ", dhcp_option($key),"\t"; if (ref($opts{$key}) =~ m/ARRAY/) { print $_, " " foreach (@{$opts{$key}}); } # NOTE: elsif can just be else, as a string # necessarily does or does not match /ARRAY/ elsif (ref($opts{$key}) !~ /ARRAY/) { print $opts{$key}; } print "\n"; } # OR (untested): for my $key (keys %opts) { print "$key ", dhcp_option($key), "\t", ( ref($opts{$key}) =~ /ARRAY/ ? join" ", @{$opts{$key}} : $opts{$key} ) "\n"; }

Replies are listed 'Best First'.
Re^2: Advice on script
by Util (Priest) on Oct 21, 2011 at 19:00 UTC
    In your point 4, I think that all the $i++ are intentional, although a bad fit for the for loop. If my refactoring is correct, then I recommend this equivalent code:
    while (@options) { my $option = hex shift @options; last if $option == 255; # end of DHCP Options my $length = hex shift @options; push @{$opts{$option}}, splice( @options, 0, $length ); }