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
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |