Perl CGI  «Prev  Next»

Lesson 10Setting and reading cookies
ObjectiveLearn how to set and read cookies.

Setting and Reading Cookies in Raku

In Raku (formerly known as Perl 6), cookie management is typically handled in the context of a web framework, like Cro, Bailador, or HTTP::Easy. However, even without a full framework, you can still read and set cookies in a web application or CGI script.
Here's how to set and read cookies in Raku:
✅ Setting Cookies in Raku (Perl 6)
You send cookies to the browser by writing them in the `Set-Cookie` HTTP header. 🔹 Example: Set a Cookie Manually
say "Set-Cookie: user=Thomas; Path=/; HttpOnly";
say "Content-Type: text/html\n";

say "<html><body>Cookie set!</body></html>";

> This must be part of your HTTP response header before sending content.
✅ Reading Cookies in Raku (Perl 6)
You can read incoming cookies from the `HTTP_COOKIE` environment variable.
🔹 Example: Read Cookies from the Request
my %cookies = $*ENV<HTTP_COOKIE>
    .split(';')
    .map({ .trim.split('=', 2) })
    .map({ $_[0] => $_[1] })
    .Hash;

say "Content-Type: text/plain\n";
say "User: " ~ (%cookies // 'No user cookie found');

✅ Example: Full CGI-style Raku Script
#!/usr/bin/env raku

# Set a cookie
say "Set-Cookie: user=Thomas; Path=/; HttpOnly";
say "Content-Type: text/html\n";

# Read cookies from incoming request
my %cookies = $*ENV<HTTP_COOKIE>
    .split(';')
    .map({ .trim.split('=', 2) })
    .map({ $_[0] => $_[1] })
    .Hash;

say "<html><body>";
say "User cookie: " ~ (%cookies<user> // 'none');
say "</html></body>";


✅ Using a Web Framework: Cro
If you are using Cro (a modern Raku web framework):
🔹 Set a Cookie
response(200, 'OK', [
    Set-Cookie => 'user=Thomas; Path=/'
], 'Cookie set!');
🔹 Read a Cookie
my $user = request.headers{'cookie'}.substr(/'user=' (.*?)(\;|\z)/)[0];

🧠 Summary
Task Raku Code Snippet
Set Cookie say "Set-Cookie: key=value; Path=/; HttpOnly"
Read Cookie my %cookies = $*ENV<HTTP_COOKIE>...
Framework Use Cro's Set-Cookie header and request header parsing


Legacy Perl Cookie Setting


Set Perl Cookie - Quiz

Click the quiz link below for another exciting and challenging (and brief) multiple choice quiz on cookies.
Set Perl Cookie - Quiz

SEMrush Software