Skip to content

Instantly share code, notes, and snippets.

@kwakwaversal
Last active September 18, 2017 14:27
Show Gist options
  • Save kwakwaversal/8977275 to your computer and use it in GitHub Desktop.
Save kwakwaversal/8977275 to your computer and use it in GitHub Desktop.
Method to check a string only contains ASCII characters #perl
# is_within_ascii
#
# Returns a copy of the string if it is within ascii. If it is outside of the
# range, it will raise an error.
sub is_within_ascii {
my $string = shift;
# look for anything that isn't ascii or pass
$string =~ /([^\x{00}-\x{7f}])/ or return $string;
# explain why we failed
my $dec = ord($1);
my $hex = sprintf '%02x', $dec;
die "$string -- char $+[0] not ASCII (it's $dec dec / $hex hex)\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment