Perl ... adding to a list - end, middle, start
Archive - Originally posted on "The Horse's Mouth" - 2008-07-09 01:05:15 - Graham EllisYou can add an extra element on to a Perl list with push, into the middle with splice and onto the beginning with unshift.
You can extract a single element from splitting a scalar and calling up the element you want using square brackets and the appropriate subscript.
Example:
open (fh,"../../requests.xyz") or die;
@x = <fh>;
push(@x,"aaron Perl Ruby Opal\n");
unshift(@x,"bob C Lua Matlab Perl Python\n");
splice(@x,3,0,"chris Lua PHP Perl Java\n");
foreach $emp (@x) {
if ($emp =~ /Python/) {
$name = (split(/\s+/,$emp))[0];
push @pythoners,$name;
}
}
Here's the result of running that:
BirthdayBoy:csr1 grahamellis$ perl skillz
Python with bob hazel leane olivia adam barry harry ken nigel rupert
bob C Lua Matlab Perl Python
antonia Perl XML PHP Tcl/Tk MySQL
barbara Tcl/Tk ASP Ruby Java
chris Lua PHP Perl Java
cherry Perl Java Ruby MySQL
delia XML PHP Java ASP
ethel MySQL Perl Tcl/Tk ASP
florence Ruby PHP Java ASP
BirthdayBoy:csr1 grahamellis$
If you want to take something off a list ... pop off the end, shift off the beginning, and splice - again - to take items out of the middle.