Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Skipping parameters in sprintf %, elegantly

by brycen (Monk)
on Aug 19, 2008 at 18:24 UTC ( [id://705294]=perlquestion: print w/replies, xml ) Need Help??

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

# Dear Monks, # use strict; subroutine(10); subroutine(20); sub subroutine { my $param = shift; #Starting with this printf "package=%s file=%s line=%s param=%d\n",caller(),$param; #Is there a more elegant way to skip the package=%s parameter: printf 'file=%2$s line=%3$d param=%4$d %5$s',caller(),$param,"\n"; #Such as a % command that would eat the given parameter? printf "%Zfile=%s line=%s param=%d\n",caller(),$param; }

Replies are listed 'Best First'.
Re: Skipping parameters in sprintf %, elegantly
by ambrus (Abbot) on Aug 19, 2008 at 19:11 UTC

    But to make your code self-documenting, the best practice might actually be

    my($package, $file, $line) = caller(); sprintf "file=%s line=%s param=%d\n", $file, $line, $param;
Re: Skipping parameters in sprintf %, elegantly
by kyle (Abbot) on Aug 19, 2008 at 18:30 UTC
    printf "file=%s line=%s param=%d\n", (caller())[1,2], $param;
Re: Skipping parameters in sprintf %, elegantly
by ambrus (Abbot) on Aug 19, 2008 at 18:56 UTC

    Yes, "%.0s"

      Perfect! Thanks.
Re: Skipping parameters in sprintf %, elegantly
by psini (Deacon) on Aug 19, 2008 at 19:00 UTC

    In sprintf you can specify for each command the position in the list from which the value must be taken. I think this is a feature present from v.5.8, not sure...

    In your example you can do:

    printf "file=%2\$s line=%3\$s param=%4\$d\n",caller(),$param;

    to skip the first parameter.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Re: Skipping parameters in sprintf %, elegantly
by gone2015 (Deacon) on Aug 19, 2008 at 18:44 UTC

    Array slicing, eg:

    printf "l=%s p=%s f=%s", (caller)[2, 0, 1] ;

      (caller)[2, 0, 1] is a LIST SLICE not an array slice, there is no array there.

        I regret that the distinction between an ARRAY and a LIST in Perl is lost on me :-(. I humbly beg that you initiate me into this mystery.

Re: Skipping parameters in sprintf %, elegantly
by ambrus (Abbot) on Aug 19, 2008 at 19:02 UTC

    Alternately "file=%2\$s line=%3\$s param=%4\$d\n". Note that the indexing starts by 1.

    Update: fixed typo in code where one of the \$ was \% instead.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-19 20:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found