Perl
Online Perl Compiler
Your script runs with perl main.pl on Perl 5.40, with the core modules. Output isn’t buffered here, so a prompt printed with print shows before <STDIN> waits for your input.
Try it aboveHow Perl runs here
- Versions
- Perl 5.40
- Run
perl main.pl- Limits per run
- 256 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
A Perl script that reads input
This main.pl counts the words in a sentence with a hash and a regular expression, then sorts by count and then alphabetically:
use strict; use warnings; print "Enter a sentence: "; my $line = <STDIN>; chomp $line; my %count; $count{lc $_}++ for $line =~ /\w+/g; for my $word (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) { printf "%-6s %d\n", $word, $count{$word}; }
$ perl main.pl Enter a sentence: the cat saw the dog and the cat ran the 3 cat 2 and 1 dog 1 ran 1 saw 1
Reading input in Perl
- my $line = <STDIN>; reads one line, newline included. chomp it before comparing or printing.
- my @lines = <STDIN>; waits for the end of input, and a while (<STDIN>) loop only stops there. This terminal never sends one, so read a count first, or stop on an empty line: last if $line eq '';
- For numbers on one line: my @n = split ' ', <STDIN>;
What isn’t available here
- CPAN. cpan and cpanm need the network, so modules such as JSON::XS, Moose, DBI and Mojolicious aren’t there. Core modules such as List::Util, Scalar::Util, POSIX, Data::Dumper, Time::Piece, Getopt::Long and JSON::PP are there.
- Your own modules work: put Utils.pm next to main.pl and use lib '.'; use Utils;
Errors you’ll see
- “Global symbol "$total" requires explicit package name (did you forget to declare "my $total"?)” use strict wants every variable declared with my.
- “Can't locate JSON/XS.pm in @INC (you may need to install the JSON::XS module)” A CPAN module. Use JSON::PP, which has the same interface.
- “Use of uninitialized value $name in concatenation (.) or string” A warning: the variable is undef, often from input you didn’t read or a hash key that isn’t there.
- “Argument "abc" isn't numeric in addition (+)” A warning: text used as a number counts as 0.
Questions
Which Perl version does this use?
Perl 5.40, run as perl main.pl.
Can I install modules from CPAN?
No. Runs have no network. The core modules that come with Perl, such as List::Util and JSON::PP, are available.
How do I read user input in Perl online?
my $line = <STDIN>; chomp $line; then type the input in the terminal while the script runs.