Clipboard Operations in Perl for Mac OS X

Like usual, there are a couple of things I want to remember here. I do a lot of work in Win32 with ActiveState’s perl. Win32 has OLE access and a cool module for accessing the clipboard through a simple object. Switching to OS “Ten” (not OSex) caused me some pain at first. pb[copy|paste] come in handy. Also, I have my .profile set to “UTF-8 everything”, so I need binmode on the files. This is also good for converting the encoding of exported java stuff (like Java-produced XML), which I think comes out as Mac Roman by default. Finally, note the newline cheat. This was necessary to “assist” the copy and paste operation from the PDF annotations.

#!/usr/bin/perl

# SET UP
$c = '_edits.txt';
$p = '_edits2.txt';

# DO IT
&edit();

# SUBS 
sub edit() {
    `pbpaste > ${c}`;

    open(MYFILE, "<", "${c}");
    binmode(MYFILE, ":utf8");
    @contents = <MYFILE>;
    close(MYFILE);

    $string = "";
    foreach $line (@contents) {
        $string .= &editLine($line);
    }
    $string =~ s/:!EOLMDASH!://ig;
    $string =~ s/^\s+//ig;
    $string =~ s/\. $//ig;

    open(MYFILE, ">", "${p}");
    binmode(MYFILE, ":utf8");
    print MYFILE $string;
    close(MYFILE);

    `pbcopy < ${p}`;

}

sub editLine () {
    my ($line) = @_;
    $line =~ s/^"//ig;
    $line =~ s/"$//ig;
    $line =~ s/\012\015?|\015\012?/ /ig; #Replace Newlines
    $line =~ s/-\W/:!EOLMDASH!:/ig;
    $line =~ s/\x{0027}/'/ig; #UTF-8 Apostrophe
    $line =~ s/\x{2018}/'/ig; #UTF-8 Single Quote
    $line =~ s/\x{2019}/'/ig; #UTF-8 Single Quote    
    $line =~ s/\x{201C}/\x{0022}/ig; #UTF-8 (?) Dbl Quote
    $line =~ s/\x{201D}/\x{0022}/ig; #UTF-8 (?) Dbl Quote

    #print $line."\\n\n";
    return " ".$line;
}

~/.profile
export __CF_USER_TEXT_ENCODING=0x1F5:0x8000100:0x8000100