6

This is what I tried:

my $s = "s" x 1000;
my $r = `echo $s |more`;

But it doesn't work, my program exits directly...

lexer
  • 1,027
  • 3
  • 14
  • 18

2 Answers2

9

It does not work in your example, because you never print $r. The output is captured in the variable $r. By using system() instead, you can see the output printed to STDOUT, but then you cannot use the output as you (probably) expected.

Just do:

print $r;

Update: I changed say to print, since "echo" already gives you a newline.

To escape shell meta characters, as mentioned in the comments, you can use quotemeta.

You should also be aware that | more has no effect when capturing output from the shell into a variable. The process is simply: echo | more | $r, and you might as well skip more.

TLP
  • 66,756
  • 10
  • 92
  • 149
  • How to escape the string when passing to bash? – lexer Sep 08 '11 at 13:35
  • You can use [quotemeta](http://perldoc.perl.org/functions/quotemeta.html). Or you can escape characters yourself, if you know what to look for. – TLP Sep 08 '11 at 13:39
3

try with the system() command :

my $s = "s" x 1000;
my $r = system("echo $s |more");

will display all your 's', and in $r you will have the result (0 in this case) of the command.

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • 1
    What if `$s` contains special characters ? Is there a function to do shell_escape alike stuff? – lexer Sep 08 '11 at 13:24
  • quotemeta is the wrong tool because it's for quoting regexp special characters, not shell special characters. – daxim Sep 11 '11 at 20:09