Acrux
view release on metacpan or search on metacpan
lib/Acrux/Util.pm view on Meta::CPAN
return '' unless length $s;
$h->{'%'} //= '%'; # by default '%' eq '%''
$s =~ s/
(?:
%\{(\w+)\} # short name like %{name}
|
%([%a-zA-Z]) # single character specifier like %d
)
/
( $1
? ( defined($h->{$1}) ? $h->{$1} : exists($h->{$1}) ? '' : "\%{$1}" )
: $2
? ( defined($h->{$2}) ? $h->{$2} : exists($h->{$2}) ? '' : "\%$2" )
: ''
)
/sgex;
return $s;
}
sub randchars {
my $l = shift || return '';
return '' unless $l =~/^\d+$/;
my $arr = shift;
my $r = '';
my @chars = ($arr && ref($arr) eq 'ARRAY') ? (@$arr) : (0..9,'a'..'z','A'..'Z');
$r .= $chars[(int(rand($#chars+1)))] for (1..$l);
return $r;
}
sub truncstr {
my $string = shift // '';
my $cutoff = shift || 0;
my $marker = shift // '.';
# Get dots dumber
my $dots = 0;
$cutoff = 3 if $cutoff < 3;
if ($cutoff < 6) { $dots = $cutoff - 2 }
else { $dots = 3 }
# Real length of cutted string
my $reallenght = $cutoff - $dots;
# Input string is too short
return $string if length($string) <= $cutoff;
# Truncate
my $fix = floor($reallenght / 2);
my $new_start = substr($string, 0, ($reallenght - $fix)); # Start part of string
$new_start =~ s/\s+$//; # trim
my $new_midle = $marker x $dots; # Middle part of string
my $new_end = substr($string, (length($string) - $fix), $fix); # Last part of string
$new_end =~ s/^\s+//; # trim
return sprintf ("%s%s%s", $new_start, $new_midle, $new_end);
}
sub indent {
my $str = shift // '';
my $ind = floor(shift || 0);
my $chr = shift // ' ';
return $str unless $ind && $ind <= 65535;
return join '', map { ($chr x $ind) . $_ . "\n" } split /\n/, $str;
}
sub words {
my @in;
foreach my $r (@_) {
if (ref($r) eq 'ARRAY') { push @in, @$r } else { push @in, $r }
}
my %o;
my $i = 0;
foreach my $s (@in) {
$s = trim($s // '');
next unless length($s) && !ref($s);
foreach my $w (split(/[\s;,]+/, $s)) {
next unless length($w);
$o{$w} = ++$i unless exists $o{$w};
}
}
return [sort {$o{$a} <=> $o{$b}} keys %o ];
}
# File utils
sub touch {
my $fn = shift // '';
return 0 unless length($fn);
my $t = time;
my $ostat = open my $fh, '>>', $fn;
unless ($ostat) {
carp("Can't touch file \"$fn\": $!");
return 0;
}
close $fh if $ostat;
utime($t, $t, $fn);
return 1;
}
sub eqtime {
my $src = shift // '';
my $dst = shift // '';
return 0 unless length($src);
return 0 unless length($dst);
unless ($src && -e $src) {
carp("Can't get access and modification times of file \"$src\": no file found");
return 0;
}
unless (utime((stat($src))[8,9], $dst)) {
carp("Can't change access and modification times on file \"$dst\": $!");
return 0;
}
return 1;
}
sub slurp {
my $file = shift // '';
my $args = @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {};
return unless length($file) && -r $file;
my $cleanup = 1;
# Open filehandle
my $fh;
if (ref($file)) {
$fh = $file;
$cleanup = 0; # Disable closing filehandle for passed filehandle
} else {
( run in 0.581 second using v1.01-cache-2.11-cpan-39bf76dae61 )