Cn-Util

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

 [`structure`]

 - A reference that is already being described further out is now shown as `(cycle)` only when it leads back to the container that holds it, and as `(shown above)` otherwise. It used to be called `(cycle)` whenever it was cut off, so in `[$a, $b]` wi...

 [`execute`]

 - The output returned for `'stdout'`, `'stderr'` and `'all'` now loses its trailing newline whatever the caller's `$/` is. Under a caller's `local $/;` the newline used to be left on.

 [`json_file_to_ref`]

 - A file holding only a bare `NaN`, `Infinity` or `-Infinity`, as Python's `json.dumps(float('nan'))` writes it, now reads as `undef`. It used to die in `decode_json`.

 [`file2string`]

 - The file is now read with the `:raw` layer, as the documentation always said. On Windows, where perl reads through `:crlf` by default, `"\r\n"` used to come back as `"\n"`; elsewhere nothing changes.

 [Documentation]

 - `format_commas` says that it rounds the binary number perl holds, not the decimal the caller wrote, so `1.005`, held as 1.00499999999999989... in a double, gives `1.00`, as `sprintf('%.2f')` does.

0.0242 2026-11-14 CST (Claude Opus 5.5 helped)

Changes  view on Meta::CPAN

 - A recursive listing no longer goes through `File::Find`, and takes less than half the CPU time in perl: 0.43 s of user time against 1.06 s over 279,000 entries. It returns the same paths.

 - A recursive listing dies with "Cannot open directory" and the path, as a non-recursive one does, when `dir` is a file, when it does not exist, and when a subdirectory cannot be read. A file used to be returned as the only result, and the other two...

 [`structure`]

 - `structure` and `st` take 43% less memory and 30% less time on a large array of records: 237 MB and 1.4 s, down from 413 MB and 2.0 s, for 300,000 five-key records. They no longer copy every value they merge at each level. The output is unchanged.

 [`json_file_to_ref`]

 - A file with neither `NaN` nor `Infinity` in it is no longer scanned for them before decoding. The scan took seven times as long as the decoding: 2.1 s for a 43 MB file that decodes in 0.3 s.

 [`file2string`]

 - A directory, or a file whose read fails, dies with "can't read" and the name. It used to return `undef`.

 [`ref_to_json_file`]

 - The file name after "Wrote" is colored only when `STDOUT` is a terminal, or `CLICOLOR_FORCE` is set, and `NO_COLOR` is not, as `structure` already decided. Output sent to a file or a pipe used to carry the escape codes.

 [`p` and `np`]

Changes  view on Meta::CPAN

 - Input that the caller had already read ahead from `STDIN` is no longer lost. In `printf 'a\nb\nc\n' | perl -e 'while (<STDIN>) { print; execute("true") }'` only `a` was printed. The command's standard input was the null device, put on fd 0 under p...

 - `STDIN` is restored when `Capture::Tiny::capture` dies. It used to stay on the null device for the rest of the program.

 - A return mode with a trailing newline, such as `"exit\n"`, is rejected before the command runs. It used to run the command and then die with "broke pigeonholes".

 - `$die` is read as true or false, as documented. `'yes'` used to die with "isn't numeric", and `2` used to mean "do not die".

 [`format_commas`]

 - Infinity and NaN are returned as perl prints them, rather than as `Inf.NaN`, `-Inf.NaN` and `NaN.NaN`.

 [`ref_to_json_file`]

 - A write that fails, such as on a full disk, dies with "can't write" and the file name. It used to print "Wrote" and return the name of a truncated file on perl 5.20 and earlier, and die with "unable to close filehandle" on later perls.

 [Argument checks]

 - `dir` with an undefined `tests`, `dir`, `regex` or `cpu`, and `structure` with an undefined `output` or `color`, die saying which argument it was, instead of "Use of uninitialized value". `dir` rejects an `on_match` that is not a code reference, w...

0.023 2026-11-02 CST (Claude Opus 5.5 helped)

Changes  view on Meta::CPAN

 - A `dir` that is a symbolic link to a directory is listed through the link in every mode. A recursive listing with the default `cpu => 1` returned nothing for one, because `File::Find` took the link for a file, while a non-recursive listing and a r...

 - `dir => '///'` returns `/etc` and the like. Only a single trailing slash after something other than a slash was removed, so it returned `////etc`.

 [`format_commas`]

 - `format_commas($n, '%.0u')` rounds half up to a whole number. The documented way to ask for a whole number appended the hundredths of any fraction without a decimal point: `1234.56` came out as `1,23456`, and `0.4` as `040`.

 [`json_file_to_ref`]

 - A bare `NaN`, `Infinity` or `-Infinity` is turned into `null` only outside JSON strings. Text inside a string that looked like one in value position was rewritten too, so `"values: [1, NaN, 2]"` was read as `"values: [1, null, 2]"`.

 [`random_key` and `random_value`]

 - Both leave the hash's iterator at the start, as they did before 0.01. 0.01 left it one pair in, so an `each` loop over the same hash afterwards skipped its first pair.

 [`p` and `np`]

 - A `p` or `np` of the calling package's own is kept when the stub for the other one loads DDP. DDP exports both, so a package with its own `p` that called `np` had that `p` replaced by DDP's.

 - A `p` or `np` called again after DDP failed to load dies again. It looped forever, because the package was marked as loaded before the load was tried.

README.md  view on Meta::CPAN

Returns the whole of a file as one string, read without any decoding layer.  A file that cannot be opened or read, such as a directory, dies, naming it.

## format_commas

    format_commas(1234567.891);         # '1,234,567.89'
    format_commas(1234567, '%.0u');     # '1,234,567'
    format_commas(999999.999);          # '1,000,000.00'
    format_commas(-0.5);                # '-0.50'
    format_commas(1e20);                # '100,000,000,000,000,000,000.00'

Puts a comma between each group of three digits of the integer part and appends the hundredths, rounded half up.  The second argument is the `sprintf` format the hundredths are printed with, `'.%02d'` by default; `'%.0u'` rounds half up to a whole nu...

What is rounded is the number perl holds, which is binary, not the decimal written in the source.  Most decimal fractions have no exact binary form, so a value written as exactly half a cent is stored a little above or below it, and rounds accordingl...

## json_file_to_ref

    my $ref = json_file_to_ref('results.json');

Reads a JSON file and returns the decoded data, through `JSON::MaybeXS`.  Python's `json` module and NumPy write `NaN`, `Infinity` and `-Infinity` as bare words, which are not JSON; where one of those stands as a value, or is the whole document, it i...

## ref_to_json_file

    ref_to_json_file($data, 'results.json');   # prints "Wrote results.json"

Writes a data structure to a file as JSON, through `JSON::MaybeXS`, prints `Wrote` and the file name, and returns the file name.  The name is colored by the rule `structure`'s `color => 'auto'` follows: when `STDOUT` is a terminal, or `CLICOLOR_FORCE...

## random_key, random_value

    my $key   = random_key(\%hash);

lib/Cn/Util.pm  view on Meta::CPAN

}

sub format_commas { # https://stackoverflow.com/questions/33442240/perl-printf-to-use-commas-as-thousands-separator
	my ($n, $format) = @_;
	$format = '.%02d' unless defined $format;
	# '%.0u' is the documented way to ask for a whole number, but sprintf
	# prints nothing for it only when the hundredths are 0: 1234.56 came out
	# "1,23456".  So '%.0u' is recognised here, rounds half up to a whole
	# number, and prints no fraction at all.
	my $whole = $format eq '%.0u';
	# Infinity and NaN are returned as perl prints them.  Run through the
	# arithmetic below they came out "Inf.NaN", "-Inf.NaN" and "NaN.NaN".
	# $n - $n is NaN for exactly these, and NaN is the one value not equal to
	# itself.
	my $diff = $n - $n;
	return "$n" if $diff != $diff;
	my $neg = $n < 0;
	my $abs = abs $n;
	my ($int, $cents);
	if ($whole) {
		$int   = int($abs + .5);
		$cents = 0;
	} else {

lib/Cn/Util.pm  view on Meta::CPAN

	return $sign . reverse(join(',', unpack('(A3)*', reverse $digits))) . ($whole ? '' : sprintf($format, $cents));
}

sub json_file_to_ref {
	my ($json_filename) = @_;
	die "$json_filename doesn't exist or isn't a file" unless -f $json_filename;
	die "$json_filename has 0 size" if -s $json_filename == 0;
	open my $fh, '<:raw', $json_filename or die "can't read $json_filename: $!";
	my $json = do { local $/; <$fh> }; # slurp; $/ restored immediately
	close $fh;
	# Python/NumPy emit bare NaN / Infinity / -Infinity, which are not valid
	# JSON. Rewrite them to null (-> undef) only when they sit in JSON value
	# position (after '[', ',' or ':', or as the whole document, which Python
	# writes for json.dumps(float('nan')) and which used to reach decode_json
	# unchanged and die there).  That test alone also matched text
	# inside a string -- "values: [1, NaN, 2]" became "values: [1, null, 2]"
	# -- so the first alternative matches each whole string literal and
	# (*SKIP)(*FAIL) resumes the scan after its closing quote.
	#
	# That scan is slow: on a 43 MB file of 300,000 records it took 2.1 s, to
	# decode_json's 0.30 s (Cpanel::JSON::XS), measured 2026-11-09.  The two
	# index() calls that rule it out took 4.5 ms there, so a file with neither
	# word, which is most of them, is not scanned at all.
	$json =~ s/"(?:[^"\\]++|\\.)*+"(*SKIP)(*FAIL)|(?:\A|[\[,:])\s*\K-?(?:NaN|Infinity)(?=\s*(?:[,\]}]|\z))/null/gs
		if index($json, 'NaN') >= 0 || index($json, 'Infinity') >= 0;
	require JSON::MaybeXS; # ~4.3 ms
	return JSON::MaybeXS::decode_json($json);
}

# These return *some* key/value from the hash, not a random one -- whichever
# pair the hash's internal iterator yields first.
#
# They used to be `foreach my $key (keys %{$hash}) { return $key }`, which is
# O(n): `keys` in list context materializes EVERY key into a temporary list,
# and then the loop throws all but the first away.  On a 50,000-key hash that

lib/Cn/Util.pm  view on Meta::CPAN

Returns the whole of a file as one string, read without any decoding layer.  A file that cannot be opened or read, such as a directory, dies, naming it.

=head2 format_commas

 format_commas(1234567.891);         # '1,234,567.89'
 format_commas(1234567, '%.0u');     # '1,234,567'
 format_commas(999999.999);          # '1,000,000.00'
 format_commas(-0.5);                # '-0.50'
 format_commas(1e20);                # '100,000,000,000,000,000,000.00'

Puts a comma between each group of three digits of the integer part and appends the hundredths, rounded half up.  The second argument is the C<sprintf> format the hundredths are printed with, C<'.%02d'> by default; C<'%.0u'> rounds half up to a whole...

What is rounded is the number perl holds, which is binary, not the decimal written in the source.  Most decimal fractions have no exact binary form, so a value written as exactly half a cent is stored a little above or below it, and rounds accordingl...

=head2 json_file_to_ref

 my $ref = json_file_to_ref('results.json');

Reads a JSON file and returns the decoded data, through C<JSON::MaybeXS>.  Python's C<json> module and NumPy write C<NaN>, C<Infinity> and C<-Infinity> as bare words, which are not JSON; where one of those stands as a value, or is the whole document,...

=head2 ref_to_json_file

 ref_to_json_file($data, 'results.json');   # prints "Wrote results.json"

Writes a data structure to a file as JSON, through C<JSON::MaybeXS>, prints C<Wrote> and the file name, and returns the file name.  The name is colored by the rule C<structure>'s C<< color =E<gt> 'auto' >> follows: when C<STDOUT> is a terminal, or C<...

=head2 random_key, random_value

 my $key   = random_key(\%hash);

t/format_commas.t  view on Meta::CPAN

is( format_commas(-1000000.99), '-1,000,000.99', 'negative with grouping' );
is( format_commas(-1234, '%.0u'), '-1,234',      'negative integer format' );
# A value that rounds away to zero is not reported as "-0.00".
is( format_commas(-0.001), '0.00', 'rounds to zero, so no sign' );

# --- Large magnitudes must not fall into scientific notation. ---
# --- int(1e20) stringifies as "1e+20", which grouping shredded to "1e,+20". ---
is( format_commas(1e20), '100,000,000,000,000,000,000.00', '1e20 groups as digits' );
is( format_commas(1e15), '1,000,000,000,000,000.00',       '1e15 groups as digits' );

# --- Infinity and NaN are returned as perl prints them, which differs between
# --- perls ("Inf" from 5.22, "inf" on 5.10.1); 0.023 gave "Inf.NaN".
my $inf = 9**9**9;
my $nan = -sin($inf);
is( format_commas($inf),  "$inf",     'Inf is returned unchanged' );
is( format_commas(-$inf), "${\-$inf}", '-Inf is returned unchanged' );
is( format_commas($nan),  "$nan",     'NaN is returned unchanged' );

done_testing;

t/json.t  view on Meta::CPAN

#!/usr/bin/env perl
# json_file_to_ref() / ref_to_json_file(): JSON round-trip, plus the
# NaN/Infinity -> null rewrite that json_file_to_ref performs for
# Python/NumPy-emitted files.
require 5.010001;
use strict;
use warnings FATAL => 'all';
use Test::More;
use Test::Exception;
use Capture::Tiny 'capture';
use File::Temp qw(tempfile tempdir);
use File::Spec;
use Cn::Util;

t/json.t  view on Meta::CPAN

	($said) = capture { ref_to_json_file($data, $out) };
	like( $said, qr/\AWrote \e\[/, '...unless CLICOLOR_FORCE is set' );
	$ENV{NO_COLOR} = 1;
	($said) = capture { ref_to_json_file($data, $out) };
	is( $said, "Wrote $out\n", '...and NO_COLOR outranks CLICOLOR_FORCE' );
}

my $back = json_file_to_ref($out);
is_deeply( $back, $data, 'data survives a write/read round trip' );

# --- NaN / Infinity handling ---
my $nan = File::Spec->catfile($dir, 'nan.json');
open my $nfh, '>', $nan or die $!;
print $nfh '{"a": NaN, "b": [1, Infinity, -Infinity], "c": "NaN in string"}';
close $nfh;

my $ref = json_file_to_ref($nan);
ok( !defined $ref->{a},    'bare NaN becomes undef' );
is( $ref->{b}[0], 1,       'real numbers next to Infinity are preserved' );
ok( !defined $ref->{b}[1], 'bare Infinity becomes undef' );
ok( !defined $ref->{b}[2], 'bare -Infinity becomes undef' );
is( "$ref->{c}", 'NaN in string',
	'the literal text "NaN" inside a string is NOT rewritten' );

# Inside a string, NaN after '[', ',' or ':' looks like a value to a pattern
# that does not know where strings begin and end; these used to be rewritten.
my $instr = File::Spec->catfile($dir, 'instr.json');
open my $ifh, '>', $instr or die $!;
print $ifh '{"msg": "values: [1, NaN, 2]", "esc": "q\\": NaN}", "x": [1, NaN], "k:NaN,": -Infinity}';
close $ifh;
$ref = json_file_to_ref($instr);
is( $ref->{msg}, 'values: [1, NaN, 2]', 'NaN in value position inside a string is left alone' );
is( $ref->{esc}, 'q": NaN}', 'an escaped quote does not end the string early' );
ok( !defined $ref->{x}[1], 'a bare NaN after the strings is still rewritten' );
ok( exists $ref->{'k:NaN,'} && !defined $ref->{'k:NaN,'},
	'a key holding ":NaN," is left alone, and its -Infinity value is rewritten' );

# A bare NaN or -Infinity as the whole document, as Python's
# json.dumps(float('nan')) writes it.  Up to 0.0242 it reached decode_json
# unchanged and died.  A backend that refuses a top-level scalar refuses the
# null it becomes, too, so the test skips there.
SKIP: {
	require JSON::MaybeXS;
	skip 'this JSON backend refuses a top-level scalar', 2
		unless eval { JSON::MaybeXS::decode_json('null'); 1 };
	for my $text ("NaN", " -Infinity\n") {
		my $top = File::Spec->catfile($dir, 'top.json');
		open my $tfh, '>', $top or die $!;
		print $tfh $text;
		close $tfh;
		my $got = eval { json_file_to_ref($top) };
		(my $shown = $text) =~ s/\s+//g;
		ok( !$@ && !defined $got, "a document of only $shown, whitespace around it or not, is read as undef" );
	}
}



( run in 2.692 seconds using v1.01-cache-2.11-cpan-60884a8df76 )