Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Literal Source Parameters At Runtime

by tomazos (Deacon)
on Oct 29, 2007 at 04:53 UTC ( #647786=perlquestion: print w/replies, xml ) Need Help??

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

I want to take the literal source code of the parameter of a function call, and use it as a string at runtime. ( a similiar fashion to the # operator in the context of a macro definition in the C/C++ preprocessor.)

sub literalize { ???? } sub assert($) { my ($condition) = @_; my $literal_condition_code = literalize(@_); if ($condition) { print "assertion failed: $literal_condition_code\n"; } } assert(42 == 24);


assertion failed: 42 == 24

The C/C++ code would be:

#define assert(condition) { if (!condition) { printf("assertion failed +: %s\n", #condition); } }

Anyone know how to do something like this in Perl?


Replies are listed 'Best First'.
Re: Literal Source Parameters At Runtime
by BrowserUk (Patriarch) on Oct 29, 2007 at 05:10 UTC

    Take a look at Smart::Comments

    c:\>perl -MSmart::Comments -lw ### assert: 42 == 42 ### assert: 42 == 43 ^Z ### 42 == 43 was not true at - line 2. c:\>perl -MSmart::Comments -lw ### assert: 42 == 42 my $var = 43; ### assert: $var == 42 ^Z ### $var == 42 was not true at - line 3. ### $var was: 43

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Literal Source Parameters At Runtime
by tuxz0r (Pilgrim) on Oct 29, 2007 at 15:37 UTC
    perl also has the -P option , which passes the program through the C preprocessor before exectution. So, using that option, you could use the exact same approach as you are in C++, using a #define.
    #! /usr/bin/perl -P use strict; #define assert(exp) { if (!(exp)) { printf("assertion failed %s\n", #e +xp); } } my $var = 30; assert($var == 32); exit 0;
    assertion failed 30 == 32

    echo S 1 [ Y V U | perl -ane 'print reverse map { $_ = chr(ord($_)-1) } @F;'

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2023-12-10 20:19 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (41 votes). Check out past polls.