
FishMonger
Veteran
/ Moderator
Aug 21, 2014, 9:19 AM
Post #14 of 17
(6656 views)
|
Re: [matteoguglielmi] Argument Passing: How To Get This Working
[In reply to]
|
Can't Post
|
|
Personally, I don't like using 1 liners except for simple one off tasks and never for important production code. One liners are more difficult to troubleshoot and maintain, especially when they start to get long and complicated. In every single case I've seen, one liner scripts lack proper error checking/handling. Here's a working one liner.
perl -ple 'BEGIN {$reg=shift; $str=shift; $cnt=shift;} last if $i; if(/$reg/) {s/$reg/eval($str) x $cnt/ee; $i++}' -- '(\d+)' '$1' 2 textfile Here's how I'd do it (but with additional error checking).
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; my $cnt = 1; GetOptions ( "reg|r=s" => \my $pattern, "str|s=s" => \my $replace, "file|f=s" => \my $file, "cnt|c=i" => \$cnt ) or die "Error in command line arguments\n"; open my $fh, '<', $file or die "failed to open '$file' <$!>"; while (<$fh>) { s/$pattern/eval($replace) x $cnt/ee; print; } close $fh; Executed as:
./script.pl -r '(\d+)' -s '$1' -c 2 -f textfile If the plan is to do inplace editing like your other one liner examples, it would be an easy adjustment to the script to accommodate that need.
|