Arjun Bora
Arjun Bora

Reputation: 437

execute shell commands from perl script

I want to rename *.DIF files to *.SUC files But the following script is giving "sh: bad substitution" error I cannot use "rename" becuase my OS is not Linux.

$com="for i in *.DIF; do mv \$i \${i/DIF/SUC}; done;";
print $com."\n";
print `$com`;

Output :

for i in *.DIF; do mv $i ${i/DIF/SUC}; done;

sh: bad substitution

Upvotes: 0

Views: 973

Answers (3)

Arjun Bora
Arjun Bora

Reputation: 437

be default perl was using sh, instead of bash, which allows {//} this question helped. Finally I used :

open my $bash_handle, '| bash' or die "Cannot open bash: $!";
print $bash_handle 'for i in *.SUC; do mv $i ${i/SUC/DIF}; done;';

Upvotes: 0

Miller
Miller

Reputation: 35198

There's no need to shell out for file operations that you can easily do within Perl.

The following renames all of your .dif extension files as .suc.

use strict;
use warnings;

use File::Copy qw(move);

move($_, s/dif$/suc/r) for glob('*.dif');

Upvotes: 1

user1919238
user1919238

Reputation:

If you are having problems with Perl's rename, use File::Copy, a platform-independent module for moving and copying files. It is a core module, so it should be already part of your Perl installation.

If the system command works when you enter it in the shell, but not in Perl, the most likely reason is that Perl isn't using the shell you expect. We would need more information about your system to be sure, though.

Upvotes: 1

Related Questions