perlshamason

How to create a SHA-256 hash of a string in Mason code?


I am trying to create a SHA-256 hash of a string in Mason by following the answers to the Stack Overflow question SHA256 digest in perl and using the Digest::SHA module

These are the contents of the file abc.mi that contains that code:

use Digest::SHA qw(sha256_hex);
<%init>
    my $message = 'random content';
    my $encryptedMsg = sha256_hex($message);
</%init>

But it's throwing the following error:

Undefined subroutine &Safe::Root0::HTML::Mason::Commands::sha256_hex called

Any idea why it is considering sha256_hex as undefined even though I defined it at the beginning of the file itself?

Has this got something to do with the fact this is Mason code with extension .mi?

========== EDIT ==========

Here is the solution to my query, after going through the answers posted for this question.

<%init>
    my $message = 'random content';
    my $encryptedMsg = Digest::SHA::sha256_hex($message);
</%init>

Solution

  • In Mason, your Perl code needs to be inside your tags. Anything outside of a tag is just content to be included in the output. So you want something like:

    <%init>
      use Digest::SHA qw(sha256_hex);
      my $message = 'random content';
      my $encryptedMsg = sha256_hex($message);
    </%init>