use strict;
use warnings;
my $log_dir = "dir";
my $log_pre = "file";
my $hist_size = 10;
foreach(sort {($b =~ m/(\d+)$/)[0] <=> ($a =~ m/(\d+)$/)[0]} <$log_dir/$log_pre.*>){
my $f=$_;
s/(\d+)$/$1+1/e;
if($1 >= $hist_size){ unlink $f; }else{ rename $f,$_; }
}
Nevermind shorter/quicker, this will not work properly for any processes that keep an open file descriptor to their log file (i.e. almost every daemon process), because the fd will still point at the original inode and therefore keep logging to the now rotated file. For most daemons you need to send a SIGHUP to the parent process to reinitialise the logging. Take a look at the logrotate documentation and code for more details on this. That does not invalidate your code (it obviously still works for other processes), just thought I'd mention it.
Aah, I see. Well, while I'm giving unbidden advice ;-), I've found that in situations such as you describe it is beneficial to use an SCM software such as subversion. This makes it easy for many people to collaborate without one accidentally overwriting someone else's changes and gives you a nice history of who changed what when. Also, channeling the update through a repository action gives you another hook to add custom behaviour. Just a thought.
In addition to tirwhan's most important remark, we also try to enforce the use of strict and warnings all the time, which your code doesn't: even if this is just a tiny snippet, it may contribute to spreading {bad, dangerous} programming techniques.
Also, using the ternary operator ?: just for his side effects is generally frowned upong, unless in golf or obfu, that is.
Last, even if this is to be considered only a portion of code and not a whole program, I think there's a typo in the glob: you probably mean $log_dir instead of log_dir.
Which are the side-effects of this operator? I have never experienced any...
But... you're using them, nevertheless! Generally one should use if (and else) for flow control and ?: to operate on values, e.g.
if (something) {
do 'this';
} else {
do 'that';
}
do (something ? 'this' : 'that');
Of course ?: also acts like an "if-then-else" and you can use it like that. But that's what is generally considered a side effect, since you're discarding its return value which its key feature.
perlmonks.org content © perlmonks.org and aukjan, blazar, tirwhan
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03