This is a time when spending a little bit of time thinking about the error messages can bge helpful. The error message is telling you that sed doesn't like the pattern you gave it. Specifically, sed is complaining that it doesn't understand "s/[ \t]*\n/". But in your code you're attempting to tell sed the pattern "s/[ \t]*$//\n". So somewhere, the character string "$/" is being translated to "\n". So you need to read about variable interpolation and the special variables.
Variable interpolation is when perl replaces a variables name with a variables value in certain locations (such as a double-quoted string). You can turn off the interpolation by changing the quoting method you use. In this case, changing your command to the following would do the trick:
system(q{cat text.txt|wc -l| sed 's/^[ \t]*//'|sed 's/[ \t]*$//'});
If you read about the special variables (perldoc perlvar), you'll find that $/ is the input record separator, and you might notice that the transformation from $/ to \n makes a little more sense.
Anyway as graff mentioned, you generally want to understand what the original is doing rather than blindly trying to convert the script. In this case, the original script performs several steps:
So, overall, the entire command string simply reads the number of lines in the file text.txt. Now that you know what the command string does, you could then try to convert that to perl. It's relatively easy. You first need to open the file:
open my $INPUTFILE, '<', 'text.txt' or die "Can't open file! $!";
Then read each line in the file, incrementing a counter for each line you read:
my $line_count=0; while (<$INPUTFILE>) { # read a line ++$line_count; # increment counter }
Then close the file to clean up after yourself:
close $INPUTFILE or die "close error: $!";
And now you're left with the line count in $line_count, so you can proceed with the next step in your script.
So by taking graff's advice, you'd learn more about what your original script is doing, and you'd learn more about perl faster as well when you write perl code to solve the intermediate steps rather than copying a shell script without understanding it.While your way may be a bit faster to get a working script, it'll be a longer road to truly learning perl.
...roboticus
In reply to Re: works on command line, but not from perl
by roboticus
in thread works on command line, but not from perl
by elwoodblues
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |