First, note that running untrusted code from a text file is a security risk. Your requirement seems a bit unusual, so perhaps you can explain a bit more about why you (think you) need this?

All your current sub gSort is doing is returning the string of code. To turn a string of Perl code into compiled code, you need eval. Here's one way to do this using a code reference:

use warnings; use strict; my $filename = 'globalSort.txt'; open my $fh, '<', $filename or die "$filename: $!"; chomp( my $codestr = do { local $/; <$fh> } ); # slurp close $fh; my $sort = eval "sub $codestr" or die "Failed to parse code from $filename: $@"; print "Sorting with code: $codestr\n"; my @data = (7,3,9,1); print " Input: @data\n"; my @sorted = sort $sort @data; print "Output: @sorted\n"; __END__ Sorting with code: { $a <=> $b } Input: 7 3 9 1 Output: 1 3 7 9

In reply to Re: Create sort function from a text file by haukex
in thread Create sort function from a text file by Doozer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.