do a perl command from applescript

I'd like to use Perl from AppleScript for text replacements. The snippet below works, however when the var haystackString starts to include apostrophes, this fails. I tried using AppleScript's "quoted form of" on haystackString however it fails I think because the shell command I'm using needs single quotes to enclose the commands being executed by Perl. Any tips? Thanks, Ted

set haystackString to "this this"

set findString to "this"

set replaceString to "that"


setshellscriptto ("perl -e '$s=\"" & haystackString & "\";$toFind=\"" & findString & "\";$replaceWith =\"" & replaceString & "\";$s =~ s/$toFind/$replaceWith/g;print $s;'") asstring


set testString to do shell scriptshellscript

Posted on Sep 30, 2014 3:31 PM

Reply
4 replies

Sep 30, 2014 5:45 PM in response to Ted Fitzpatrick

Hi,


Ted Fitzpatrick wrote:


however it fails I think because the shell command I'm using needs single quotes to enclose the commands being executed by Perl. Any tips? Thanks, Ted


Yes, that's right.


Solution, use the arguments:


set haystackString to "can't  can't"
set findString to "can't"
set replaceString to "that's all"

set args to (quoted form of haystackString) & " " & (quoted form of findString) & " " & quoted form of replaceString
set testString to do shell script "perl -e '$s=\"$ARGV[0]\";$s =~ s/$ARGV[1]/$ARGV[2]/g; print \"$s\"' " & args

Oct 1, 2014 9:06 AM in response to Jacques Rioux

Bonjour Jacques,


Merci for the solution! With my somewhat limited Perl knowledge, in your solution it looks like Perl has a special variable named $ARGV that's made to hold an array of arguments passed from a command line. And, I know that AppleScript's "quoted form of" is specially made for passing strings as command line args. It's nice to see that I can use these two together and not need to worry about manually escaping my string. Awesome!


Now I have a nice speedy and powerful way to do text replacement operations via Perl from my AppleScript.


Thanks,


Ted

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

do a perl command from applescript

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.