Harry: (New to thread, reading bottom-up..)
On Tue, Nov 4, 2014 at 1:12 PM, Harry Putnam <rea...@newsguy.com> wrote: > Shlomi Fish <shlo...@shlomifish.org> writes: >> 1. No need to wrap «$cmd» in double quotes here: >> >> http://perl-begin.org/tutorials/bad-elements/#vars_in_quotes >> >> 2. You should use the list form: >> >> my @cmd = qw(ls /); >> >> open my $ch, '-|', @cmd >> or die "Can't open <<@cmd>>: $!"; >> >> (Untested!). > > Ok, not so hard to do I guess. But why is this important? #1 is explained by Shlomi's URL so I'll assume you are asking about #2. The list form of opening a pipe will properly pass arguments on to the command without worrying about your shell interpreting special characters and doing something unexpected. In this case it doesn't matter because you don't have any special characters, and your command is a literal string without variable interpolation/concatenation, but to future-proof the code and also keep with "best practices" using the list form is generally a good idea (note that it isn't supported on every platform: I believe that native Windows implementations may not support it). use strict; use warnings; my $user_input = <STDIN>; # E.g., "';echo rm -fR /;echo '" my $cmd = "ls '$user_input'"; my @cmd = ('ls', $user_input); # Depending on what the user enters this could do # something wrong, or worse, destructive. open my $fh1, '|-', $cmd or die "open pipe: $!"; # This should be safe because Perl will take care to # make sure that $user_input is passed as a single # argument instead of being interpreted by your shell. open my $fh2, '|-', @cmd or die "open pipe: $!"; print STDERR "First pipe:\n"; print <$fh1>; print STDERR "Second pipe:\n"; print <$fh2>; __END__ (Horribly contrived example...) Look at the output with this example session (first line is just a command line, second line is user input): > bash$ perl example > ';echo Sneak attack!;echo ' > First pipe: > Second pipe: > ls: cannot access ';echo Sneak attack!;echo ' > : No such file or directory > ls: cannot access : No such file or directory > Sneak attack! WHOA, what is that last line of output all about?! That, good sir, is very dangerous. Avoid destructive words while testing this. The documentation is good. Please read the entirety of `perldoc -f open', but in particular look for the LIST form of opening pipes. Regards, -- Brandon McCaig <bamcc...@gmail.com> <bamcc...@castopulence.org> Castopulence Software <https://www.castopulence.org/> Blog <http://www.bambams.ca/> perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }. q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.}; tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say' -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/