Script to upload users to Moodle

In my spare time, I am a maintainer of moodle powered platforms hosted by a company that offers e-learning services and this post is about uploading new students to that platform 😀

This task generally requires a CSV file filled with information about the student. The mandatory fields are username, first name, last name and email but this is just an example and some other fields may be required. The tutor or the course owner generally provides an excel file with the necessary data but since an username is needed to login and the students may not have an email account or is not a company’s policy to use personal email addresses for login, we have take alternative measures to fit the requirements.

Here are enumerated some rules imposed for standardization:

1. Username must be the first letter of the forename followed by the first surname, no spaces in between.
2. If no email account is provided, the system will provide one for the user, even if the account doesn’t exists yet.

This is how the file looks like:
[bash]
1 Pedro Pedroso [email protected] Cobranzas
2 Juan Perez [email protected] Cobranzas
3 Juan Gonzalez [email protected] Cobranzas
4 Un boludo No tiene Por ahi

[/bash]

And this is the output from the script:
[bash]
username, password, firstname, lastname, email
ppedroso, elpassword*, Pedro, Pedroso, [email protected]
jperez, elpassword*, Juan, Perez, [email protected]
jgonzalez, elpassword*, Juan, Gonzalez, [email protected]
uboludo, elpassword*, Un, boludo, [email protected]
[/bash]

And finally, the script written in Perl. It explains itself very well I think, there is no need for line to line comment 😀

[perl]
use strict;
use warnings;

open(FILE, “< $ARGV[0]"); print "username, password, firstname, lastname, emailn"; for ()
{
if ($_=~m/([a-z|A-Z]+)s([a-z|A-Z]+)/g)
{
my $name = $1;
my $lastname = $2;
$name=~m/^w/g;
my $username = lc(“$&$lastname”);
my $mail;

if (!($_=~m/[w|_|-]+@w+.(com|net)/g))
{
$mail = lc($name.$lastname).’@example.com’;
}
else
{
$mail = $&;
}

print “$username, elpassword*, $name, $lastname, $mailn”;
}
else
{
die ($_);
}
}
[/perl]