perl if variable is json code example

Example 1: perl json response to list all the files in a directory

#!/usr/bin/perl

use JSON;
use CGI;
sub create_list_all() {
    my $i = 1;
    opendir my $dh, $dir or die "Can't open directory $dir: $!";
    foreach $file ( readdir $dh ) {
        if ( $i < 3 ) {
            $i++;
            next;
        }
        push( @list, $file );
    }
    closedir $dh;
}

print "Content-type: application/json;charset=UTF-8\n\n";

my @list;
#########insert directory path
my $dir = './';
create_list_all();
@list = sort { length $a <=> length $b || $b cmp $a } @list;
my $ret = to_json( \@list );
print $ret;
exit 0;

Example 2: perl json response to list all the files in a directory

#!/usr/bin/perl

use JSON;
use CGI;

print "Content-type: application/json;charset=UTF-8\n\n";
my $q = new CGI;
my @list;
my $dir = '/usr/amoeba/pub/b/OUHTC/etc/ERP/concur/data/to_proactive';
sub create_list_all() {
    my $i = 1;
    opendir my $dh, $dir or die "Can't open directory $dir: $!";
    foreach $file ( readdir $dh ) {
        if ( $i < 3 ) {
            $i++;
            next;
        }
        push( @list, $file );
    }
    closedir $dh;
}

create_list_all();
@list = sort { length $a <=> length $b || $b cmp $a } @list;
my $ret = to_json( \@list );
print "Content-type: application/json;charset=UTF-8\n\n";
print $ret;
exit 0;