Cn-Util

 view release on metacpan or  search on metacpan

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

		POSIX::close($saved_fd0);
	} elsif ($eof_on_fd0) {
		close $eof;
	} else {
		POSIX::close(0);
	}
	die $err unless $ok;
	# Truthiness, as the documentation describes it.  `$die == 1` made 'yes' die
	# with "isn't numeric" and made 2 mean "do not die".
	if ($die && $exit != 0) {
		say STDERR "exit = $exit";
		say STDERR "STDOUT = $stdout";
		say STDERR "STDERR = $stderr";
		die "$cmd\n failed";
	}
	return $exit if $return eq 'exit';
	# chomp removes whatever $/ is, and $/ is the caller's: under a caller's
	# `local $/;` it removed nothing, and "hi\n" came back with its newline.
	{
		local $/ = "\n";
		chomp $stdout;
		chomp $stderr;
	}
	return $stdout if $return eq 'stdout';
	return $stderr if $return eq 'stderr';
	return { exit => $exit, stdout => $stdout, stderr => $stderr };   # 'all', the only mode left
}

sub file2string {
	my ($file) = @_;
	# :raw, as the documentation promises: with the default layers, Windows
	# perls read through :crlf, and "\r\n" came back as "\n".
	open my $fh, '<:raw', $file or die "can't read $file: $!"; # was autodie
	# open() succeeds on a directory on POSIX systems.  Linux, OpenBSD and
	# FreeBSD 13+ then fail the read with EISDIR, but NetBSD's read(2) returns
	# the raw directory entries, so 0.0241 handed back binary garbage there
	# (CPAN Testers report 52217fbc-dd66-11f1-9541-8d78add113b8, perl 5.42.3,
	# amd64-netbsd-thread-multi).  So a directory is refused by fstat, whatever
	# read() would do; Windows never gets here, as its open() fails.
	if (-d $fh) {
		require POSIX;
		$! = POSIX::EISDIR();
		die "can't read $file: $!";
	}
	# readline returns undef only on an error -- an empty file reads as ''.
	# Tested with // rather than through a lexical, which on perl 5.10.1 took
	# a third copy of the file at return: a 200 MB file peaked at 575 MB,
	# against 384 MB this way (5.44 is 195 MB either way, through
	# copy-on-write).
	return do { local $/; <$fh> } // die "can't read $file: $!";
}

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 {
		$int = int $abs;
		# int(100 * (.005 + frac)) is the original expression, and is exactly
		# round-half-up to hundredths -- .005 * 100 is the +0.5 before truncation.
		# Of the binary value, not the decimal the caller wrote: 1.005 is held as
		# 1.00499999999999989... as a double, and gives 1.00, as README.md says.
		# It is kept verbatim so no already-correct result shifts by a cent.
		$cents = int(100 * (.005 + ($abs - $int)));
		# ...but it can land on 100 (.999 rounds up to 1.00), which used to be
		# printed straight into the fraction: 999999.999 came out "999,999.100".
		# The carry has to go into the integer part instead.
		if ($cents >= 100) {
			$int++;
			$cents -= 100;
		}
	}
	# Split off the sign and work on the magnitude: the old code fed a negative
	# through int()/sprintf and produced "-1,234.-49" for -1234.5, and lost the
	# sign entirely for -0.5.  A value that rounds to zero stays unsigned, so
	# -0.001 is "0.00" rather than "-0.00".
	my $sign = ($neg && ($int || $cents)) ? '-' : '';
	# '%.0f' rather than interpolating $int: a large magnitude stringifies in
	# scientific notation, and the reverse/unpack grouping shredded that into
	# "1e,+20" for 1e20.
	my $digits = sprintf '%.0f', $int;
	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
# was 1.48 ms per call; via each() it is 0.15 us, ~10,000x faster.
#
# The bare `keys` in void context resets the iterator, so repeated calls keep
# returning the first pair instead of walking off the end of the hash.  It is
# reset again after the each(), which would otherwise leave it one pair in, so
# that a caller's own `while (each %h)` afterwards skipped the first pair.
# The old `keys`-in-list-context version left it at the start, and so do these.
#
# Falling off a foreach also returned '' rather than undef in scalar context;
# each() on an empty hash returns an empty list, so these now yield a true
# undef, which is what t/random.t always asserted.
sub random_key {
	my ($hash) = @_;
	keys %{ $hash };                 # reset the iterator
	my ($key) = each %{ $hash };
	keys %{ $hash };
	return $key;
}

sub random_value {
	my ($hash) = @_;
	keys %{ $hash };                 # reset the iterator
	my (undef, $value) = each %{ $hash };
	keys %{ $hash };
	return $value;
}

sub ref_to_json_file {
	my ($ref, $json_filename) = @_;
	my $ref_json_filename = ref $json_filename;
	unless ($ref_json_filename eq '') {
		die "$json_filename isn't a scalar/string";
	}
	require JSON::MaybeXS;
	# Encoded before the file is opened, because opening it empties it: up to
	# 0.0242 a structure encode_json refused -- a cycle, a code reference --
	# died after an existing file had already been truncated to nothing.
	my $json = JSON::MaybeXS::encode_json($ref);
	open my $fh, '>:raw', $json_filename   # Write it unmangled
		or die "can't write $json_filename: $!"; # was autodie
	say $fh $json;
	# A full disk shows up at close, when the buffer is flushed.  Unchecked,
	# perl up to 5.20 reported "Wrote" and returned the name of a truncated
	# file, and later perls died with "unable to close filehandle" from the
	# implicit close under FATAL warnings.
	close $fh or die "can't write $json_filename: $!";
	# Colored by the rule structure()'s color => 'auto' follows.  Up to 0.024
	# it always was, so a log or a pipe that STDOUT went to got the escape
	# codes too.
	my $shown = $json_filename;

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

=item * C<dir> (default C<.>): The directory to list.  Trailing slashes are removed, but C</> stays C</>.  A C<dir> that is a symbolic link to a directory is listed through the link, recursively or not.

=item * C<regex> (default C<.>): A pattern the base name must match, given as a string or a C<qr//>.  An invalid pattern dies, naming it.

=item * C<tests> (default C<f>): One or more of perl's file tests, as letters: C<rwxoRWXOezsfdlpSbcugkTB>.  Every one must pass.  C<'d'> lists directories; C<''> applies no test at all.

=item * C<recursive> (default C<0>): C<1> descends into subdirectories, without following symbolic links.

=item * C<cpu> (default C<1>): For a recursive listing, the number of worker processes (through C<Parallel::ForkManager>).  Ignored when C<recursive> is C<0>.

=item * C<on_match> (no default): A code reference called with each path as it is found; C<dir> then returns an empty list, so a very large tree is never held in memory.

=back

The file tests share one C<stat> per path, so asking for four of them costs no more than asking for one.  C<-l> is checked first, with C<lstat>.

With C<cpu> greater than 1, C<dir> walks the tree breadth-first until one level holds four directories per worker, then shares those directories out.  The results are the same as a serial walk, in a different order.  C<on_match> still runs in the cal...

An unknown argument, an undefined C<tests>, C<dir>, C<regex> or C<cpu>, a letter that is not a file test, a C<cpu> that is not a positive integer, an C<on_match> that is not a code reference, and a directory that cannot be opened, whether C<dir> itse...

=head2 execute

 my $exit   = execute('make test');                  # 0, or dies
 my $out    = execute('git log -1 --format=%H', 'stdout');
 my $err    = execute('perl -c script.pl', 'stderr');
 my $all    = execute('ls /nonexistent', 'all', 0);  # does not die
 # $all = { exit => 512, stdout => '', stderr => "ls: cannot access ..." }

Runs C<$cmd> through the shell with C<system>, capturing its standard output and standard error with C<Capture::Tiny>.  The second argument says what to return:

=over

=item * C<exit> (the default): the wait status, C<$?> -- 0 for success, 256 for C<exit 1>

=item * C<stdout>: standard output, chomped

=item * C<stderr>: standard error, chomped

=item * C<all>: a hash reference with C<exit>, C<stdout> and C<stderr>

=back

The third argument, C<$die>, is true by default: a command that exits non-zero prints its exit status, standard output and standard error to C<STDERR> and dies.  Pass a false value, such as 0, to have the status returned instead.

The command's standard input is an empty pipe.  A command that would prompt -- C<rm> on a write-protected file, C<cp -i> -- reads end-of-file and declines rather than waiting, unseen, for an answer.  The caller's C<STDIN> is not touched, so input it ...

=head2 file2string

 my $text = file2string('notes.txt');

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);
 my $value = random_value(\%hash);

Return one key, or one value, of a hash -- whichever pair perl's hash iterator yields first, which is quick no matter how big the hash is.  This is I<any> key, not a randomly chosen one: the same hash returns the same pair each time.  It is useful fo...

Both reset the hash's iterator, so do not call them on a hash in the middle of an C<each> loop.

=head2 structure

 my $text = structure($ref, output => 'string');
 structure(\%config, max_depth => 2, as => 'config');

Prints the I<shape> of a data structure rather than its values: C<p> shows every element of a 50,000-element array of records, while C<structure> merges them into one and shows the record once.

 my @people = (
     { name => 'Ann', age => 31, langs => ['perl', 'R'] },
     { name => 'Bo',  age => 28, langs => [], email => undef },
 );
 st @people;

prints

 ARRAY[2]
     [*]: HASH{4} (from 2 instances)
         age: number
         email?: null
         langs: ARRAY[0-2] (from 2 instances)
             [*]: string
         name: string

A key that only some of the merged hashes have is marked C<?>.  Values in the same place that are of different kinds are shown as a C<UNION> of each kind.  Arrays show the range of their lengths.  Blessed references show their class.  A reference to ...

It takes these options after the reference:

=over

=item * C<output> (default C<stdout>): C<stdout> or C<stderr> to print there; C<string> to print nothing.  The text is returned in every case.

=item * C<color> (default C<auto>): C<1> or C<0>.  C<auto> colours the output when it goes to a terminal, or when C<CLICOLOR_FORCE> is set, unless C<NO_COLOR> is set.

=item * C<max_depth> (default C<0>): How many levels to descend before printing C<(...)>; C<0> is no limit.

=item * C<hash_max> (default C<32>): A hash with more keys than this is taken to be a lookup table, and its values are merged into one entry, C<< E<lt>*E<gt> >>, rather than listed by key.  C<0> lists every key.

=item * C<as> (no default): A line to print above the structure.

=back

=head2 st

 st %hash;



( run in 0.828 second using v1.01-cache-2.11-cpan-60884a8df76 )