Is there way to use the more command in a perl script? There is a file and I want to print its content, but since there are lots of lines I would like to print it with more . I tried putting more in backticks, but it didn't work:
open(FILE,'/opt/myfile' ) or die("Could not open file.");
`more /opt/myfile`;
`more /opt/myfile` means to capture the output of the more command into a string, which is discarded (you'd usually store the output in a variable or pass it to a function). When its output is not connected to a terminal, more is equivalent to cat, it doesn't do anything useful.
To run a subprocess in Perl without capturing its output, use the system function.
system('more', '/opt/myfile');
Note that you should pass a list containing the command and its arguments, not a mere string. If you pass a single string to system, it is passed to a shell, which will expand any special character in the file name. For example, system('more /opt/myfile') would work but system('more /opt/$(rm -rf ~)') would delete all your files. If you pass multiple arguments, no shell is involved: system('more', '/opt/$(rm -rf ~)') invokes more on that strangely-named file.
If there's any risk that the file name begins with a + or -, pass -- before the file name, to avoid having it interpreted as an option.
Rather than call more, you should check the PAGER environment variable, and call that if it is defined. $PAGER is the de facto standard pager. If the variable is not defined, in this millennium, you should default to less (if you're paranoid, default to less if it's present and more otherwise).
my $pager = $ENV{PAGER};
if (!defined $pager || $pager eq '') {
$pager = 'less';
}
system($pager, '--', '/opt/myfile');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With