Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing bash variable into inline perl script

Reference the 2nd to last line in my script. For some reason Perl is not able to access the variable $perlPort how can I fix this? Note: $perlPort is a bash variable location before my perl script

perl -e '
{
    package MyWebServer;
    use HTTP::Server::Simple::CGI;
    use base qw(HTTP::Server::Simple::CGI);
    my %dispatch = (
        "/" => \&resp_hello,
    );


    sub handle_request {
        my $self = shift;
        my $cgi  = shift;
        my $path = $cgi->path_info();
        my $handler = $dispatch{$path};
        if (ref($handler) eq "CODE") {
            print "HTTP/1.0 200 OK\r\n";
            $handler->($cgi);
        } else {
            print "HTTP/1.0 404 Not found\r\n";
            print $cgi->header,
            $cgi->start_html("Not found"),
            $cgi->h1("Not found"),
            $cgi->end_html;
        }
    }


    sub resp_hello {
        my $cgi  = shift;   # CGI.pm object
        return if !ref $cgi;
        my $who = $cgi->param("name");   
        print $cgi->header,
            $cgi->start_html("Hello"),
            $cgi->h1("Hello Perl"),
            $cgi->end_html;
    }
}


my $pid = MyWebServer->new($perlPort)->background();
print "Use 'kill $pid' to stop server.\n";'
like image 324
Pazuzu Avatar asked Sep 06 '25 17:09

Pazuzu


2 Answers

export perlPort
perl -e '
...
my $pid = MyWebServer->new($ENV{perlPort})->background();
'
like image 98
Ole Tange Avatar answered Sep 10 '25 05:09

Ole Tange


You can use -s switch to pass variables. See http://perldoc.perl.org/perlrun.html

perl -se '
...
my $pid = MyWebBrowser->new($perlPort)->background();
...' -- -perlPort="$perlPort" 
like image 35
ernix Avatar answered Sep 10 '25 04:09

ernix