Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to strip out the periods in an IP list, and pad the octets with 0 so I get a 12 digit number. (I'm not worried about the first octet truncating the leading zeros.) I'm getting an invalid subroutine on line 16, and am not really sure what I am doing wrong. Could you take a look?

Thanks,

Carrie

$pad_char = "0"; $pad_len = "3"; $padded = ""; open IN, '<ConvertMe.txt' or die; while (<IN>) { chomp; my($octet1, $octet2, $octet3, $octet4) = split(/./, $_, 4); foreach( $octet1, $octet2, $octet3, $octet4 ) { $padded = $pad_char x ( $pad_len - length( $_ ) ) . $_ ; substr($converted, legnth($padded ) ) = $padded; } open OUT, '>>Converted.txt' or die; print $converted; } close OUT; close IN;

Edited: ~Thu Jul 25 21:11:42 2002 (GMT) by footpad: Added <CODE> and other markup tags.

Replies are listed 'Best First'.
Re: simple padding of IP address
by Aristotle (Chancellor) on Jul 25, 2002 at 21:12 UTC
    See perldoc -f sprintf. my $twelve_digit_str = sprintf "%03d%03d%03d%03d", split /\./, $ip_address; Update: or even my $twelve_digit_str = sprintf "%03d" x 4, split /\./, $ip_address; ____________
    Makeshifts last the longest.
Re: simple padding of IP address
by thelenm (Vicar) on Jul 25, 2002 at 21:12 UTC
    This is a perfect job for sprintf. Try something like this:
    while (<IN>) { chomp; my $padded; $padded .= sprintf("%03d", $_) for split /\./; }

    Update: I like Aristotle's solution better. Use that one, not mine. TIMTOWTDI! :-)

    -- Mike

    --
    just,my${.02}

      Why the for loop? sprintf takes more than one argument.

      Makeshifts last the longest.

Re: simple padding of IP address
by BorgCopyeditor (Friar) on Jul 26, 2002 at 03:08 UTC

    Maybe your invalid subroutine is called "legnth"?

      substr($converted, legnth($padded ) ) = $padded;

    BCE
    --Your punctuation skills are insufficient!