Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

pass subroutine value to scalar

by sub_chick (Hermit)
on Jan 12, 2006 at 02:38 UTC ( [id://522600]=perlquestion: print w/replies, xml ) Need Help??

sub_chick has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I ran a few searches here and still have yet to find a solution to my newbie issue with a subroutine I am defining:
use strict; sub ctrl{ system ("xmmsctrl print %T"); print "\n"; }
I am trying to get the return value of this subroutine to be passed directly to a scalar variable($ctrl) so that i can take its value (artist - songtitle) and match it up with a regex.
Thank you


Es gibt mehr im Leben als Bücher, weißt du. Aber nicht viel mehr. - (Die Smiths)"

Replies are listed 'Best First'.
Re: pass subroutine value to scalar
by davido (Cardinal) on Jan 12, 2006 at 02:43 UTC

    I assume you're trying to get the return value of your system command, "xmmsctrl print %T", and not simply the return value of your sub named ctrl(). After all, the return value of ctrl() is going to be the return value of your print command, which is pretty much always '1'. You might be looking for the backticks( `` ) operator (also spelled as qx//) instead of system.

    The following snippet captures the output of xmmsctrl print %T and returns via ctrl() to $ctrl.

    use strict; sub ctrl { my $rv = `xmmsctrl print %T`; return $rv; } my $ctrl = ctrl();

    Backticks ( `` ) return the output of the command you're executing through the shell, whereas system returns the exit status of the command.


    Dave

Re: pass subroutine value to scalar
by dpuu (Chaplain) on Jan 12, 2006 at 02:46 UTC
    The subroutine as your have coded it doesn't actually have a meaningful return value. The problem is that the "system" command does not capure the output text of the command. Perl has a different operator for that:
    sub ctrl { return qx/xmmsctrl print %T/; } my $ctrl = ctrl();
    The qx operation could also be written using backticks:
    sub ctrl { return `xmmsctrl print %T`; }
    --Dave
    Opinions my own; statements of fact may be in error.
Re: pass subroutine value to scalar
by sh1tn (Priest) on Jan 12, 2006 at 04:51 UTC
    In addition - you need to pass subroutine reference:
    my $command = sub { qx'xmmsctrl print %T' }; $command->(); # subroutine dereference


      Why is that?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://522600]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-03-29 14:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found