Skip to content

Commit

Permalink
printf: hex & octal escapes (#528)
Browse files Browse the repository at this point in the history
* When testing against bash-builtin and GNU version of printf command, octal escapes allow 3 digits but input >255 are interpreted as mod-256 (e.g. \400 wraps around to \0)
* For hex escapes, only 2 digits are allowed so entering input above FF is not possible anyway
* The hex digits can be mixed case, but the "x" prefix must be lowercase
* test1: terminate word list with NUL: perl printf '%s\0' over here
* test2: windows line-ending string with hex: perl printf 'hey\xd\xa'
  • Loading branch information
mknos committed Apr 3, 2024
1 parent 3917d99 commit 67ceb17
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions bin/printf
Expand Up @@ -77,6 +77,18 @@ sub parse_fmt {
}
}

sub oct2char {
my $str = shift;
my $n = oct($str) & 255;
return chr($n);
}

sub hex2char {
my $str = shift;
my $n = hex($str) & 255;
return chr($n);
}

sub escape_str {
my $str = shift;
$str =~ s/\\a/\a/g;
Expand All @@ -86,6 +98,8 @@ sub escape_str {
$str =~ s/\\r/\r/g;
$str =~ s/\\t/\t/g;
$str =~ s/\\v/\x0b/g;
$str =~ s/\\([0-7]{1,3})/oct2char($1)/eg;
$str =~ s/\\x([0-9a-fA-F]{1,2})/hex2char($1)/eg;
return $str;
}

Expand Down

0 comments on commit 67ceb17

Please sign in to comment.