in reply to Create sort function from a text file
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Create sort function from a text file
by Doozer (Scribe) on Aug 16, 2021 at 12:31 UTC | |
by haukex (Archbishop) on Aug 16, 2021 at 13:04 UTC | |
by jdporter (Paladin) on Aug 19, 2021 at 02:55 UTC | |
by eyepopslikeamosquito (Archbishop) on Aug 19, 2021 at 05:08 UTC | |
by hippo (Archbishop) on Aug 19, 2021 at 10:30 UTC | |
| |
| |
by Corion (Patriarch) on Aug 16, 2021 at 13:04 UTC | |
by eyepopslikeamosquito (Archbishop) on Aug 17, 2021 at 08:04 UTC | |
by Marshall (Canon) on Aug 18, 2021 at 19:09 UTC |