How do you send commands to the terminal in a perl script?
For example, if I want to run the command mkdir $directory in the console, what do I type in the perl script?
How do you send commands to the terminal in a perl script?
For example, if I want to run the command mkdir $directory in the console, what do I type in the perl script?
For executing any system command from perl script you need use system command with a backtick
For e.g
In your case for creating a directory you need to type
system(mkdir $directory); #note html is not showing the backtick but backtick is place before mkdir and after $directory
It will create a dir in current working dir in the name of $directory
Modeling off the sample code in the documentation at http://perldoc.perl.org/functions/system.html:
@args = ("mkdir", $directory);
system(@args) == 0
or die "mkdir failed";
Perl can make directories without system() calls, but I assume you want to do other things and are just using mkdir as an example.
cat foo.txt puts the contents of foo.txt into $i)$i = qx{cat foo.txt} if you need to get around Markdown.Since Perl has the mkdir() system call built in, you don't need to use the system command at all:
my $directory = "...";
if (mkdir $directory)
{
croak "Failed to create directory $directory ($!)";
}
If you must use system, do so the safe way:
if (system "mkdir", $directory)
{
croak "Failed to create directory $directory";
}
This form of the system statement (with a list of arguments) avoids the problems of shell expansion.
Use perl commands instead of relying on shell commands. There are a great many things that perl can do, and if it is not already built in, or a core module, it's likely available on CPAN.
As people have mentioned, mkdir is available, and so are most of the basic file related commands.
That being said, here's the dirt on shell commands in perl:
You want the perl script to:
systemqx//, or
backticks.exec. But usually, you'll not really want to use exec, for
reasons described in the link above.open with MODE either -| or |-, respectively.exec does not return to the calling program, i.e. the perl process running the perl code is replaced by the exec'ed program. This means that code following the call to exec is never executed, unless exec fails to invoke the program.exec, beyond learning never to use it, some 10-15 years ago. =)