string chop(string s, void|int size)
{
int length = sizeof(s);
return size > 0 && size < length ? s[..length - (size + 1)] : s;
}
string str;
str = "\n";
str = "Jon \"Maddog\" Orwant";
str =
#"This is a multiline string
terminated by a double-quote like any other string";
string str, value;
int offset, count;
value = str[offset..offset+count];
value = str[offset..];
string newstring, newtail;
str = str[..offset-1]+newstring+str[offset+count..];
str = str[..offset-1]+newtail;
string leading, s1, s2, trailing;
[leading, s1, s2, trailing] = array_sscanf(str, "%5s%*3s%8s%8s%s");
array(string) fivers = str/5;
array(string) chars = str/"";
str = "This is what you have";
string first, start, rest, last, end, piece;
int t = str[0];
first = str[0..0];
start = str[5..5+1];
rest = str[13..];
last = str[sizeof(str)-1..sizeof(str)-1];
end = str[sizeof(str)-4..];
piece = str[sizeof(str)-8..sizeof(str)-8+2];
str = "This is what you have";
str = replace(str, ([ " is ":" wasn't " ]) );
str = str[..sizeof(str)-13]+"ondrous";
str = str[1..];
str = str[..sizeof(str)-11];
str = "This is what you have";
str = replace(str[..4], ([ "is":"at" ]) )+str[5..];
str = "make a hat";
[str[0], str[-1]] = ({ str[-1], str[0] });
string a, b, c;
a = "To be or not to be";
b = a[6..11];
b = a[6..7]; c=a[3..4];
write("%s\n%s\n", b, c);
string cut2fmt(int ... positions)
{
string template = "";
int lastpos = 1;
foreach(positions ;; int place)
{
template += "A" + (place - lastpos) + " ";
lastpos = place;
}
template += "A*";
return template;
}
string fmt = cut2fmt(8, 14, 20, 26, 30);
write("%s\n", fmt);
a = b || c;
if(!x)
x = y;
int foo(int c, int|void b)
{
return zero_type(b) ? c : b;
}
foo = bar || "DEFAULT VALUE";
argv = argv[1..];
dir = argv[0] || "/tmp";
dir = sizeof(argv) ? argv[0] : "/tmp";
count[shell||"/bin/sh"]++;
user = getenv("USER") || getenv("LOGNAME") || getpwuid(getuid())[0] ||
"Unknown uid number "+getuid();
if(!starting_point)
starting_point = "Greenwich";
if(!sizeof(a))
a = b;
a = (sizeof(b)?b:c);
[var1, var2] = ({ var2, var1 });
temp = a;
a = b;
b = temp;
a = "alpha";
b = "omega";
[a, b] = ({ b, a });
[alpha, beta, production] = "January March August"/" ";
[alpha, beta, production] = ({ beta, production, alpha });
int i;
i = 'a';
i = '\n';
string char = "foo";
int num = char[0];
char = String.int2char(num);
char = sprintf("%c",num);
write("Number %d is character %[0]c\n", num);
Number 101 is character e
string str;
array(int) arr;
arr = (array)str;
str = (string)arr;
int ascii_value = 'e';
string character = String.int2char(101);
write("Number %d is character %[0]c\n", 101);
array(int) ascii_character_numbers = (array(int))"sample";
write("%s\n", (array(string))ascii_character_numbers*" ");
string word = (string)ascii_character_numbers;
string word = (string)({ 115, 97, 109, 112, 108, 101 });
write(word+"\n");
string hal ="HAL";
array(int) ascii = (array)hal;
array(int) ibm = ascii[*]+1;
array(int) ibm = map(ascii, `+, 1)
write(ibm+"\n");
string hello = "Hello world!";
array(string) chars = hello/"";
foreach(chars;; string char)
;
string data = "an apple a day";
array(string) chars = data/"";
mapping(string:int) seen = ([]);
foreach(chars ;; string char)
seen[char]++;
write("unique chars are: %s\n", sort(indices(seen))*"");
string data = "an apple a day";
string result = sort(indices(mkmapping(data/"", allocate(sizeof(data))))*"";
write("unique chars are: %s\n", result);
string data = "an apple a day";
int sum;
foreach(data ;; int char)
sum += char;
write("sum is %d\n", sum);
string data = "an apple a day";
int sum=`+(@(array)data);
write("sum is %d\n", sum);
#/usr/bin/pike
void main(int argc, array(string) argv)
{
string data = Stdio.read_file(argv[1]);
int checksum;
foreach(data ;; int char)
checksum += char;
checksum %= pow(2,16)-1;
write("%d\n", checksum);
}
void main(int argc, array(string) argv)
{
string data=Stdio.read_file(argv[1]);
int checksum = `+(@(array)data) % ((1<<16)-1);
write("%d\n", checksum);
}
void main(int argc, array argv)
{
array(string) files;
int delay = 1;
if(argv[1][0] == '-')
{
files = argv[2..];
delay = (int)argv[1][1..];
}
else
files = argv[1..];
foreach(files, string file)
{
string data = Stdio.read_file(file);
foreach(data/"", string char)
{
write(char);
sleep(0.005*delay);
}
}
}
string s = "This is a string";
reverse(s);
reverse(s/" ") * " ";
(reverse(s/" ")-({ "" })) * " ";
string word = "reviver";
int is_palindrome = word==reverse(word);
void main(int argc, array(string) argv)
{
string data=Stdio.read_file(argv[1]);
foreach(data/"\n", string line)
{
if(line==reverse(line) && sizeof(line)>5)
write("%s\n", line);
}
}
string s = "This is a \n string";
string notabs=String.expand_tabs(s);
string notabs=String.expand_tabs(s, 4);
string notabs=String.expand_tabs(s, 4, "-");
string s = "This is a string";
string tabs="";
foreach(s/8.0 ;; string stop)
{
int spaces=sizeof(String.common_prefix(({ reverse(stop), " "})));
tabs+=stop[..7-spaces];
if(spaces)
tabs+="^I";
}
string notabs="";
foreach(tabs/"^I" ;; string stop)
{
notabs+=stop;
if(sizeof(stop)<8)
notabs+=" "*(8-sizeof(stop));
}
mapping(string:string) vars = ([ "$fruit$":"apple", "$desert$":"pudding" ]);
string template = "Todays fruit is $fruit$, and for desert we have $desert$";
string menu = replace(template, vars);
string upper, lower, result;
upper = "DON'T SHOUT!";
result = lower_case(upper);
lower = "speak up";
result = upper_case(lower);
result = String.capitalize(lower);
string text = "thIS is a loNG liNE";
array(string) words = text/" ";
words = lower_case(words[*]);
words = String.capitalize(words[*]);
text = words*" ";
text = String.capitalize(lower_case((text/" ")[*])[*])*" ";
void main()
{
string input;
while(input=Stdio.stdin.read(1))
write(randcap(input));
}
string randcap(string char)
{
if(random(100)<20)
char=String.capitalize(char);
return char;
}
string here=#"your text
goes here";
string there=array_sscanf((here/"\n")[*], "%*[\t ]%s")[*][0]*"\n";
array tmp=({});
foreach(here/"\n";; string line)
{
tmp+=array_sscanf(line, "%*[\t ]%s");
}
string there=tmp*"\n";
void main()
{
array(string) input = ({ "Folding and splicing is the work of an editor,",
"not a mere collection of silicon",
"and",
"mobile electrons!"});
int columns = 20;
write("0123456789"*2+"\n");
write(wrap(input*" ", 20, " ", " ")+"\n");
}
string wrap(string text, void|int width,
void|string|int nexttab, void|string|int leadtab)
{
string leadindent="";
string indent="";
string indent2="";
if(!width)
width=Stdio.stdout->tcgetattr()->columns;
if(stringp(nexttab))
{
indent=nexttab;
width-=sizeof(nexttab); }
else if(intp(nexttab))
{
indent=" "*nexttab;
width-=nexttab;
}
if(stringp(leadtab))
leadindent=leadtab;
else if(intp(leadtab))
if(leadtab > 0)
leadindent=" "*leadtab;
else if(leadtab < 0)
{
write(indent+".\n");
indent=indent[..(sizeof(indent)+leadtab)-1];
write(indent+".\n");
indent2=text[..-leadtab-1];
text=text[-leadtab..];
}
return sprintf("%^s%=*s%-=*s", indent, sizeof(indent2), indent2,
width, leadindent+text);
}
$ ./wrapdemo
01234567890123456789
Folding and
splicing is the
work of an editor,
not a mere
collection of
silicon and mobile
electrons!
inherit "wrapdemo.pike";
wrap(replace(text, "\n", " "));
foreach(Stdio.stdin->read()/"\n\n";; string para)
write(wrap(replace(para, "\n", " "))+"\n\n");
array(string) charlist=({ "%", "\\" });
string var="some input % text with \\";
var=replace(var, charlist, "\\"+charlist[*]);
var=replace(var, charlist, charlist[*]+charlist[*]);
string line=" foo\n\t ";
array(string) many=({ " bar\n\t ", " baz\t " });
line=String.trim_whites(line);
many=String.trim_whites(many[*]);
line=String.trim_all_whites(line);
many=String.trim_all_whites(many[*]);
write("Lookup user: ");
string user = String.soundex(Stdio.stdin.gets());
foreach(get_all_users(), array u)
{
string firstname="", lastname="";
sscanf(u[4], "%s %s,", firstname, lastname);
if( user==String.soundex(u[0]) ||
user==String.soundex(firstname) ||
user==String.soundex(lastname) )
write("%s: %s %s\n", u[0], firstname, lastname);
}
string number="123.3asdf";
int|float realnumber= (int)number;
string rest;
[realnumber, rest] = array_sscanf(number, "%d%s");
int same(float one, float two, int accuracy)
{
return sprintf("%.*f", accuracy, one) == sprintf("%.*f", accuracy, two);
}
int wage=536;
int week=40*wage;
write("one week's wage is: $%.2f\n", week/100.0);
float unrounded=3.5;
string rounded=sprintf("%.*f", accuracy, unrounded);
float a=0.255;
string b=sprintf("%.2f", a);
write("Unrounded: %f\nRounded: %s\n", a, b);
write("Unrounded: %f\nRounded: %.2f\n", a, a);
string bin=sprintf("%b", 5);
int dec=array_sscanf("0000011111111111111", "%b")[0];
int num = array_sscanf("0110110", "%b")[0];
string binstr = sprintf("%b", 54);
string dec2bin(int n)
{
return sprintf("%b",n);
}
int bin2dec(string n)
{
return array_sscanf(n, "%b")[0];
}
foreach(enumerate(y-x+1,1,x);; int val)
{
}
for(int i=x; i<=y; i++)
{
}
for(int i=x; i<=y; i+=7)
{
}
foreach(enumerate(y-x+1,7,x);; int val)
{
}
write("Infancy is: ");
foreach(enumerate(3);; int val)
{
write("%d ", val);
}
write("\n");
write("Toddling is: %{%d %}\n", enumerate(2,1,3));
write("Childhood is: ");
for (int i = 5; i <= 12; i++)
{
write("%d ", i);
}
write("\n");
int arabic;
string roman = String.int2roman(arabic);
array nums=enumerate(10001);
array romans=String.int2roman(nums[*]);
mapping roman2int = mkmapping(romans, nums);
int arabic = roman2int[roman];
string roman_fifteen = String.int2roman(15);
write("Roman for fifteen is %s\n", roman_fifteen);
int arabic_fifteen = roman2int[roman_fifteen];
write("Converted back, %s is %d\n", roman_fifteen, arabic_fifteen);
int y,x;
int rand = random(y-x+1)+x;
float y,x;
float rand = random(y-x+1)+x;
int rand = random(51)+25;
write("%d\n", rand);
array arr;
mixed elt = arr[random(sizeof(arr))];
mixed elt = random(arr);
array chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@$%^&*"/"";
string password = "";
for(int i=1; i<=8; i++)
{
password+=random(chars);
}
string password = random((({chars})*8)[*])*"";
string password = random_string(8);
string password = MIME.encode_base64(random_string(8))[..7];
random_seed(int seed);
random_seed((int)argv[1]);
float gaussian_rand()
{
float u1, u2, w, g1, g2;
do
{
u1 = 2.0 * random(1.0) - 1.0; u2 = 2.0 * random(1.0) - 1.0;
w = u1 * u1 + u2 * u2;
} while (w > 1.0);
w = sqrt((-2.0 * log(w)) / w); g2 = u1 * w; g1 = u2 * w;
return g1;
}
float mean = 25.0, sdev = 2.0;
float salary = gaussian_rand() * mean + sdev;
write("You have been hired at: %.2f\n", salary);
float deg2rad(float deg)
{
return (deg / 180.0) * Math.pi;
}
float rad2deg(float rad)
{
return (rad / Math.pi) * 180.0;
}
write("%f\n", Math.convert_angle(180, "deg", "rad"));
write("%f\n", deg2rad(180.0));
float degree_sin(float deg)
{
return sin(deg2rad(deg));
}
float rad = deg2rad(380.0);
write("%f\n", sin(rad));
write("%f\n", degree_sin(380.0));
float my_tan(float theta)
{
return sin(theta) / cos(theta);
}
float theta = 3.7;
write("%f\n", my_tan(theta));
write("%f\n", tan(theta));
float value = 100.0;
float log_e = log(value);
float log_10 = Math.log10(value);
float log_base(float base, float value)
{
return log(value) / log(base);
}
float answer = log_base(10.0, 10000.0);
write("log(10, 10,000) = %f\n", answer);
Math.Matrix a = Math.Matrix( ({ ({3, 2, 3}), ({5, 9, 8}) }) ),
b = Math.Matrix( ({ ({4, 7}), ({9, 3}), ({8, 1}) }) );
Math.Matrix c = a * b;
Math.Matrix t = c->transpose();
int dec = 867;
string hex = sprintf("%x", dec);
string oct = sprintf("%o", dec);
int dec;
string hex = "363"; sscanf(hex, "%x", dec);
int dec;
string oct = "1543"; sscanf(oct, "%o", dec);
int number;
write("Gimme a number in decimal, octal, or hex: ");
sscanf(Stdio.stdin->gets(), "%D", number);
write("%d %x %o\n", number, number, number);
string commify_series(int series)
{
return reverse((reverse((string)series) / 3.0) * ",");
}
int hits = 3452347;
write("Your website received %s accesses last month.\n", commify_series(hits));
string commify(string s)
{
function t = lambda(string m) { return reverse((reverse(m) / 3.0) * ","); };
return Regexp.PCRE("([0-9]+)")->replace(s, t);
}
int hits = 3452347;
string output = sprintf("Your website received %d accesses last month.", hits);
write("%s\n", commify(output));
string pluralise(int value, string root, void|string singular_, void|string plural_)
{
string singular = singular_ ? singular_ : "";
string plural = plural_ ? plural_ : "s";
return root + ( (value > 1) ? plural : singular );
}
int duration = 1;
write("It took %d %s\n", duration, pluralise(duration, "hour"));
write("%d %s %s enough.\n", duration, pluralise(duration, "hour"),
pluralise(duration, "", "is", "are"));
duration = 5;
write("It took %d %s\n", duration, pluralise(duration, "hour"));
write("%d %s %s enough.\n", duration, pluralise(duration, "hour"),
pluralise(duration, "", "is", "are"));
string plural(string singular)
{
mapping(string : string) e2 =
(["ss":"sses", "ph":"phes", "sh":"shes", "ch":"ches",
"ey":"eys", "ix":"ices", "ff":"ffs"]);
mapping(string : string) e1 =
(["z":"zes", "f":"ves", "y":"ies", "s":"ses", "x":"xes"]);
foreach(({e2, e1}), mapping(string : string) endings)
{
foreach(indices(endings), string ending)
{
if (has_suffix(singular, ending))
{
return replace(singular, ending, endings[ending]);
}
}
}
return singular;
}
int main()
{
foreach(aggregate("mess", "index", "leaf", "puppy"), string word)
write("%6s -> %s\n", word, plural(word));
}
void main(int n, array args)
{
foreach(args[1..], string arg)
{
mapping r = ([]);
foreach(Math.factor((int)arg), int f)
r[f]++;
write("%-10s", arg);
if(sizeof(r)==1)
write(" PRIME");
else
{
foreach(sort(indices(r)), int f)
{
write(" %d", f);
if(r[f]>1) write("**%d", r[f]);
}
}
write("\n");
}
}
write("Today is day %d of the current year.\n", localtime(time())->yday+1);
write("Today is day %d of the current year.\n", Calendar.now()->year_day());
int day, month, year;
mapping now=localtime(time());
year = now->year+1900;
month = now->mon+1;
day = now->mday;
write("The current date is %04d %02d %02d\n", year, month, day);
object now=Calendar.now();
year = now->year_no();
month = now->month_no();
day = now->month_day();
write("The current date is %04d %02d %02d\n", year, month, day);
write("The current date is %04d %02d %02d\n", @lambda(){ return ({ now->year_no(), now->month_no(), now->month_day() }); }(Calendar.now()));
Calendar.dwim_time("2:40:25 23.11.2004");
Calendar.dwim_time("2:40:25 23.11.2004")->unix_time();
Calendar.dwim_time("2:40:25 UTC 23.11.2004");
Calendar.parse("%Y-%M-%D %h:%m:%s %z","2004-11-23 2:40:25 UTC");
Calendar.Second(2004, 11, 23, 2, 40, 25);
Calendar.Year(2004)->month(11)->day(23)->hour(2)->minute(40)->second(25);
Calendar.Day(2004, 11, 23)->set_timezone("UTC")->hour(2)->minute(40)->second(25);
Calendar.dwim_time("2:40:25");
Calendar.dwim_time("2:40:25 UTC");
Calendar.parse("%h:%m:%s %z","2:40:25 UTC");
Calendar.Day()->set_timezone("UTC")->hour(2)->minute(40)->second(25);
int unixtime=1101174025;
int day, month, year;
mapping then=localtime(unixtime);
year = then->year+1900;
month = then->mon+1;
day = then->mday;
write("Dateline: %02d:%02d:%02d-%04d/%02d/%02d\n", then->hour, then->min, then->sec, then->year+1900, then->mon+1, then->mday);
object othen=Calendar.Second(unixtime);
write("Dateline: %02d:%02d:%02d-%04d/%02d/%02d\n", othen->hour_no(),
othen->minute_no(), othen->second_no(), othen->year_no(),
othen->month_no(), othen->month_day());
int days_offet=55;
int hour_offset=2;
int minute_offset=17;
int second_offset=5;
object then=Calendar.parse("%D/%M/%Y, %h:%m:%s %p","18/Jan/1973, 3:45:50 pm")
+Calendar.Day()*days_offet
+Calendar.Hour()*hour_offset
+Calendar.Minute()*minute_offset
+Calendar.Second()*second_offset;
write("Then is %s\n", then->format_ctime());
write("To be precise: %d:%d:%d, %d/%d/%d\n",
then->hour_no(), then->minute_no(), then->second_no(),
then->month_no(), then->month_day(), then->year_no());
int years = 1973;
int months = 1;
int days = 18;
int offset = 55;
object then = Calendar.Day(years, months, days)+offset;
write("Nat was 55 days old on: %d/%d/%d\n", then->month_no(), then->month_day(),then->year_no());
int bree = 361535725;
int nat = 96201950;
int difference = bree-nat;
write("There were %d seconds between Nat and Bree\n", difference);
int seconds = difference % 60;
int minutes = (difference / 60) % 60;
int hours = (difference / (60*60) ) % 24;
int days = (difference / (60*60*24) ) % 7;
int weeks = difference / (60*60*24*7);
write("(%d weeks, %d days, %d:%d:%d)\n", weeks, days, hours, minutes, seconds);
object bree = Calendar.dwim_time("16 Jun 1981, 4:35:25");
object nat = Calendar.dwim_time("18 Jan 1973, 3:45:50");
object difference = nat->range(bree);
write("There were %d days between Nat and Bree\n", difference/Calendar.Day());
int days=difference/Calendar.Day();
object left=difference->add(days,Calendar.Day)->range(difference->end());
write("Bree came %d days, %d:%d:%d after Nat\n",
days,
(left/Calendar.Hour())%24,
(left/Calendar.Minute())%60,
(left/Calendar.Second())%60,
);
array(int) breakdown_elapsed(object u, void|array on)
{
array res=({});
if (!on) on=({Day,Hour,Minute,Second});
foreach (on;;program|TimeRange p)
{
if (u==u->end()) { res+=({0}); continue; }
int x=u/p;
u=u->add(x,p)->range(u->end());
res+=({x});
}
return res;
}
write("Bree came %d days, %d:%d:%d after Nat\n",
@breakdown_elapsed(difference));
mapping day=localtime(time());
day->mday;
day->wday;
day->yday;
int year=1981;
int month=6;
int day=16;
object date;
date = Calendar.Day(year, month, day);
date->week_day();
date->week_no();
date->year_day();
write("%d/%d/%d was a %s\n", month, day, year, date->week_day_name());
write("in the week number %d.\n", date->week_no());
string date = "1998-06-03";
int yyyy;
int mm;
int dd;
[yyyy, mm, dd] = array_sscanf(date, "%d-%d-%d");
object day;
day=Calendar.dwim_day(date);
day=Calendar.parse("%Y-%M-%D", date);
day->unix_time();
day->year_no();
day->month_no();
day->month_day();
object now=Calendar.dwim_time("Sun Sep 21 15:33:36 1997");
now->format_ctime();
now = Calendar.Second(1973, 1, 18, 3, 45, 50);
write("strftime gives: %s %02d/%02d/%!2d\n", now->week_day_name(),
now->month_no(), now->month_day(), now->year_no());
now->format_nice();
now->week()->format_nice();
now->format_nicez();
now->hour()->format_nicez();
now->format_ext_time();
now->format_ext_ymd();
now->format_iso_time();
now->format_iso_ymd();
now->format_mod();
now->format_month();
now->format_month_short();
now->format_mtime();
now->format_time();
now->format_time_short();
now->format_time_xshort();
now->format_tod();
now->format_tod_short();
now->format_todz();
now->format_todz_iso();
now->format_week();
now->format_week_short();
now->format_iso_week();
now->format_iso_week_short();
now->format_xtime();
now->format_xtod();
now->format_ymd();
now->format_ymd_short();
now->format_ymd_xshort();
now->format_ctime();
now->format_smtp();
now->format_http();
int t=time();
float t0=time(t);
float t1=time(t);
float elapsed=t1-t0;
write("Press return when ready: ");
array(int) before=System.gettimeofday();
Stdio.stdin->gets();
array(int) after=System.gettimeofday();
int elapsed_sec=after[0]-before[0];
int elapsed_usec=after[1]-before[1];
if(elapsed_usec<0)
{
elapsed_sec--;
elapsed_usec+=1000000;
}
write("You took %d.%d seconds.\n", elapsed_sec, elapsed_usec);
int main()
{
gaugethis(5000000, 100, lambda(){ return random(pow(2,31)-1); });
gaugethis(50000, 100, lambda(){ return pow(2,64)+random(pow(2,64)); });
gaugethis(500000, 100, lambda(){ return random_string(10); });
}
void gaugethis(int size, int number_of_times, function rand)
{
array gauged_times = ({});
float average;
int swidth=sizeof((string)size);
int nwidth=sizeof((string)number_of_times);
for(int i; i<number_of_times; i++)
{
write("%*d: ", nwidth, i);
array(int) arr=({});
write("creating array: ");
for(int j; j<size; j++)
{
arr += ({ rand() });
}
write(" sorting: ");
float gaugetime=gauge
{
arr=sort(arr);
};
gauged_times += ({ gaugetime });
write(" %f \r", gaugetime);
}
average=`+(@gauged_times)/(float)number_of_times;
gauged_times=sort(gauged_times);
write("average: %O, min: %O, max: %O \n",
average, gauged_times[0], gauged_times[-1]);
}
int abort_on_signal=1;
sleep(0.25, abort_on_signal);
delay(0.25);
Calendar.dwim_time("Tue, 26 May 1998 23:57:38 -0400")->distance(
Calendar.dwim_time("Wed, 27 May 1998 05:04:03 +0100"))->format_elapsed();
int main()
{
MIME.Message mail = MIME.Message(Stdio.stdin.read());
array received = reverse(mail->headers->received/"\0");
Calendar.Second lasttime = Calendar.dwim_time(mail->headers->date);
array delays=({ ({ "Sender", "Recipient", "Time", "Delta" }) });
delays+=({ ({ mail->headers->from,
array_sscanf(received[0], "from %[^ ]")[0],
mail->headers->date,
""
}) });
foreach(received;; string hop)
{
string fromby, date;
[fromby, date] = hop/";";
Calendar.Second thistime = Calendar.dwim_time(date);
delays+= ({ array_sscanf(fromby, "from %[^ ]%*sby %[^ ]%*s") +
({ date, lasttime->distance(thistime)->format_elapsed() })
});
lasttime=thistime;
}
write("%{%-=22s %-=22s %-=20s %=10s\n%}\n", delays);
return 0;
}
array flat = ({ "this", "that", "the", "other" });
array nested = ({ "this", "that", ({ "the", "other" }) });
array tune = ({ "The", "Star-Spangled", "Banner" });
tune[0];
tune[1];
array(string) flat = ({ "this", "that", "the", "other" });
array(string|array(string)) admit1 = ({ "this", "that", ({ "the", "other" }) });
array(array) require1 ({ ({ "this", "that" }), ({ "the", "other" }) });
array(string) a = ({ "quick", "brown", "fox" });
array(string) a = "Why are you teasing me?"/" ";
array(string) lines = #"The boy stood on the burning deck,
It was as hot as glass."/"\n";
array(string) bigarray = Stdio.read_file("mydatafile")/"\n";
array(string) ships = "Niña Pinta Santa María"/" ";
array(string) ships = ({ "Niña", "Pinta", "Santa María" });
array(array(string)) lists =
({
({ "just one thing" }),
({ "Mutt", "Jeff" }),
({ "Peter", "Paul", "Mary" }),
({ "To our parents", "Mother Theresa", "God" }),
({ "pastrami", "ham and cheese", "peanut butter and jelly", "tuna" }),
({ "recycle tired, old phrases", "ponder big, happy thoughts" }),
({ "recycle tired, old phrases",
"ponder big, happy thoughts",
"sleep and dream peacefully" }),
});
void main()
{
write("The list is: %s.\n", commify_list(lists[*])[*]);
}
string commify_list(array(string) list)
{
switch(sizeof(list))
{
case 1: return list[0];
case 2: return sprintf("%s and %s", @list);
default:
string seperator=",";
int count;
while(count<sizeof(list) && search(list[count], seperator)==-1)
count++;
if(count<sizeof(list))
seperator=";";
return sprintf("%{%s"+seperator+" %}and %s",
list[..sizeof(list)-2], list[-1]);
}
}
void what_about_that_array(array list)
{
write("The array now has %d elements.\n", sizeof(list));
write("The index of the last element is %d.\n", sizeof(list)-1);
write("Element #3 is %O.\n", list[3]);
}
array people = ({ "Crosby", "Stills", "Nash", "Young" });
what_about_that_array(people);
people=people[..sizeof(people)-2];
what_about_that_array(people);
people+=allocate(10001-sizeof(people));
what_about_that_array(people);
array people = ({ "Crosby", "Stills", "Nash", "Young" });
people[10000]=0;
foreach(list; int index; mixed item)
{
}
foreach(bad_users;; object user)
{
complain(user);
}
complain(bad_users[*]);
foreach(sort(indices(getenv()));; string var)
{
write("%s=%s\n", var, getenv(var));
}
foreach(getenv(); string var; string value)
{
write("%s=%s\n", var, value);
}
foreach(all_users;; string user)
{
int disk_space = get_usage(user);
if(disk_space > MAX_QUOTA)
complain(user);
}
object pipe=Stdio.File();
Process.create_process(({ "who" }), ([ "stdout":pipe->pipe() ]));
foreach(pipe->line_iterator();; string line)
{
if(search(line, "tchrist")>-1)
write(line+"\n");
}
object fh=Stdio.File("somefile");
foreach(fh->line_iterator(); int linenr; string line)
{
foreach(Process.split_quoted_string(line);; string word)
{
write(reverse(word));
}
}
array(int) list = ({ 1,2,3 });
foreach(list;; int item)
{
item--;
}
write("%{%d %}\n", list);
foreach(list; int index;)
{
list[index]--;
}
write("%{%d %}\n", list);
array a = ({ 0.5, 3 });
array b = ({ 0, 1 });
array a_ = a[*]*7;
array b_ = b[*]*7;
write("%{%O %}\n", a_+b_);
string scalar = " abc ";
array(string) list = ({ " a ", " b " });
mapping(mixed:string) hash = ([ "a":" a ", "b":" b " ]);
scalar = String.trim_whites(scalar);
list = String.trim_whites(list[*]);
foreach(hash; int key;)
{
hash[key]=String.trim_whites(hash[key]);
}
mapping seen = ([]);
array uniq = ({});
foreach(list;; mixed item)
{
if(!seen[item])
seen[item] = 1;
else
uniq += ({ item });
}
mapping seen = ([]);
array uniq = ({});
foreach(list;; mixed item)
{
if(!seen[item]++)
uniq += ({ item });
}
mapping seen = ([]);
array uniq = ({});
foreach(list;; mixed item)
{
if(!seen[item]++)
some_func(item);
}
mapping seen = ([]);
array uniq = ({});
foreach(list;; mixed item)
{
seen[item]++;
}
uniq = indices(seen);
array uniq = indices(({ list[*],1 }));
array uniq = list&indices(({ list[*],1 }));
object pipe = Stdio.File();
Process.create_process(({ "who" }), ([ "stdout":pipe->pipe() ]));
mapping ucnt = ([]);
foreach(pipe->line_iterator();; string line)
{
ucnt[(line/" ")[0]]++;
}
array users = sort(indices(ucnt));
write("users logged in: %s\n", users*" ");
array A = ({ 1, 2, 3 });
array B = ({ 2, 3, 4 });
array aonly = A-B;
array a = ({ 1, 3, 5, 6, 7, 8 });
array b = ({ 2, 3, 5, 7, 9 });
array union = a|b;
array intersection = a&b;
array difference = a-b;
array symdiff= a^b;
array members = ({ "Time", "Flies" });
array initiates = ({ "An", "Arrow" });
members += initiates;
members = members[..1]+({ "Like" })+members[2..];
write("%s\n", members*" ");
members[0] = "Fruit";
members = members[..sizeof(members)-3]+({ "A", "Banana" });
write("%s\n", members*" ");
array reversed = reverse(arr);
foreach(reverse(arr);; mixed item)
{
}
for(int i=sizeof(arr)-1; i<=0; i--)
{
}
array ascending = sort(users);
array descending = reverse(sort(users));
array descending = Array.sort_array(users, lambda(mixed a, mixed b)
{
return a<b;
}
);
array arr = ({ 0,1,2,3,4,5,6,7,8,9 });
int n=3;
array front = arr[..n-1];
arr = arr[n..];
array back = arr[sizeof(arr)-n..];
arr = arr[..sizeof(arr)-(n+1)];
array shift2(ADT.Queue queue)
{
return ({ queue->read(), queue->read() });
}
ADT.Queue friends = ADT.Queue("Peter", "Paul", "Mary", "Jim", "Tim");
string this, that;
[this, that] = shift2(friends);
ADT.Stack beverages = ADT.Stack();
beverages->set_stack(({ "Dew", "Jolt", "Cola", "Sprite", "Fresca" }));
array pair = beverages->pop(2);
array shift2(ADT.CircularList list)
{
return ({ list->pop_front(), list->pop_front() });
}
array pop2(ADT.CircularList list)
{
return reverse( ({ list->pop_back(), list->pop_back() }) );
}
ADT.CircularList friends = ADT.CircularList( ({"Peter", "Paul", "Mary", "Jim", "Tim"}) );
string this, that;
[this, that] = shift2(friends);
ADT.CircularList beverages = ADT.CircularList( ({ "Dew", "Jolt", "Cola", "Sprite", "Fresca" }) );
array pair = pop2(beverates);
mixed match = search(arr, element);
int test(mixed element)
{
if(sizeof(element)==5)
return 1;
else
return 0;
}
mixed match = Array.search_array(arr, test);
if(match != -1)
{
}
else
{
}
if( (multiset)arr[element] )
{
}
else
{
}
array matching=({});
foreach(list;; mixed element)
{
if(test(element))
matching+=({ element });
}
array matching = map(list, test)-({ 0 });
array matching = test(list[*])-({ 0 });
array(int) unsorted = ...;
array(int) sorted = sort(unsorted);
array(string) unsorted = ({ "123asdf", "3poiu", "23qwert", "3ayxcv" });
sort((array(int))unsorted, unsorted);
array unordered;
int compare(mixed a, mixed b)
{
}
array ordered = Array.sort_array(unordered, compare);
int compute(mixed element)
{
}
array precomputed = map(unordered, compute);
sort(precomputed, unordered);
array ordered = unordered;
sort(map(unordered, compute), unordered);
sort(compute(unordered[*]), unordered);
array ordered = sort(employees, lambda(mixed a, mixed b)
{
return a->name > b->name;
}
);
foreach(Array.sort_array(employees,
lambda(mixed a, mixed b){ return a->name > b->name; })
;; mixed employee)
{
write("%s earns $%d\n", employee->name, employee->salary);
}
array ordered_employees =
Array.sort_array(employees,
lambda(mixed a, mixed b){ return a->name > b->name; });
foreach(ordered_employees;; mixed employee)
{
write("%s earns $%d\n", employee->name, employee->salary);
}
mapping bonus;
foreach(ordered_employees;; mixed employee)
{
if(bonus[employee->id])
write("%s got a bonus!\n", employee->name);
}
array sorted = Array.sort_array(employees,
lambda(mixed a, mixed b)
{
if(a->name!=b->name)
return (a->name < b->name)
return (b->age < a->age);
}
);
array(array) users = System.get_all_users();
sort(users);
array user;
while(user=System.getpwent())
{
users += ({ user[2], user });
}
System.endpwent();
sort(users);
array(array) users = System.get_all_users();
sort(users[*][2], users);
write(users[*][0]*"\n");
write("\n");
array names;
array sorted = Array.sort_array(names, lambda(mixed a, mixed b)
{
return a[1] < b[1];
}
);
sort(names[*][1], names);
sorted=names;
array strings;
array sorted = Array.sort_array(strings, lambda(mixed a, mixed b)
{
return sizeof(a) < sizeof(b);
}
);
sort(sizeof(strings[*]), strings);
sorted=strings;
array strings;
array temp = map(strings, sizeof);
sort(temp, strings);
array sorted = strings;
array strings;
sort(map(strings, sizeof), strings);
sort(sizeof(strings[*]), strings);
sorted=strings;
array fields;
array temp = map(fields, array_sscanf, "%*s%d%*s");
sort(temp, fields);
array sorted_fields=fields;
sort(array_sscanf(fields[*], "%*s%d%*s"), fields);
array sorted_fields=fields;
array passwd_lines = (Stdio.read_file("/etc/passwd")/"\n")-({""});
array(array) passwd = passwd_lines[*]/":";
int compare(mixed a, mixed b)
{
if(a[3]!=b[3])
return (int)a[3]<(int)b[3];
if(a[2]!=b[2])
return (int)a[2]<(int)b[2];
return a[0]<b[0];
}
array sorted_passwd = Array.sort_array(passwd, compare);
sort( passwd[*][0], passwd);
sort( ((array(int))passwd[*][2]), passwd);
sort( ((array(int))passwd[*][3]), passwd);
ADT.CircularList circular;
circular->push_front(circular->pop_back());
circular->push_back(circular->pop_front());
mixed grab_and_rotate(ADT.CircularList list)
{
mixed element = list->pop_front();
list->push_back(element);
return element;
}
ADT.CircularList processes = ADT.CircularList( ({ 1, 2, 3, 4, 5 }) );
while(1)
{
int process = grab_and_rotate(processes);
write("Handling process %d\n", process);
sleep(1);
}
array arr;
Array.shuffle(arr);
array set_shuffle(array list)
{
multiset elements=(multiset)list;
list=({});
while(sizeof(elements))
{
mixed pick=random(elements);
list+=({ pick });
elements[pick]--;
}
return list;
}
array list;
list=set_shuffle(list);
inherit "mjd_permute";
int permutations = factorial(sizeof(list));
array shuffle = list[n2perm(random(permutations)+1, sizeof(list))[*]];
void naive_shuffle(array list)
{
for(int i=0; i<sizeof(list); i++)
{
int j=random(sizeof(list)-1);
[ list[i], list[j] ] = ({ list[j], list[i] });
}
}
void main()
{
array words=Stdio.stdin.read()/"\n"; int maxlen=sort(sizeof(words[*]))[-1]; maxlen++;
int cols = Stdio.stdout->tcgetattr()->columns/maxlen;
int rows = (sizeof(words)/cols) + 1;
string mask="%{%-"+maxlen+"s%}\n";
words=Array.transpose(words/rows); write(mask, words[*]); }
int factorial(int n)
{
int s=1;
while(n)
s*=n--;
return s;
}
write("%d\n", factorial(500));
void main()
{
string line;
while(line=Stdio.stdin->gets())
{
permute(line/" ");
}
}
void permute(array items, array|void perms)
{
if(!perms)
perms=({});
if(!sizeof(items))
write((perms*" ")+"\n");
else
{
foreach(items; int i;)
{
array newitems=items[..i-1]+items[i+1..];
array newperms=items[i..i]+perms;
permute(newitems, newperms);
}
}
}
mapping fact=([ 1:1 ]);
int factorial(int n)
{
if(!fact[n])
fact[n]=n*factorial(n-1);
return fact[n];
}
array n2pat(int N, int len)
{
int i=1;
array pat=({});
while(i <= len)
{
pat += ({ N%i });
N/=i;
i++;
}
return pat;
}
array pat2perm(array pat)
{
array source=indices(pat);
array perm=({});
while(sizeof(pat))
{
perm += ({ source[pat[-1]] });
source = source[..pat[-1]-1]+source[pat[-1]+1..];
pat=pat[..sizeof(pat)-2];
}
return perm;
}
array n2perm(int N, int len)
{
return pat2perm(n2pat(N, len));
}
void main()
{
array data;
while(data=Stdio.stdin->gets()/" ")
{
int num_permutations = factorial(sizeof(data));
for(int i; i<num_permutations; i++)
{
array permutation = data[n2perm(i, sizeof(data))[*]];
write(permutation*" "+"\n");
}
}
}
mapping age = mkmapping( ({ "Nat", "Jules", "Josh", }), ({ 24, 25, 17 }) );
mapping age = ([]);
age["Nat"] = 24;
age["Jules"] = 25;
age["Josh"] = 17;
age->Nat = 24;
age->Jules = 25;
age->Josh = 17;
mapping age = ([ "Nat":24, "Jules":25, "Josh":17 ]);
mapping(string:string) food_color = ([
"Apple":"red",
"Banana":"yellow",
"Lemon":"yellow",
"Carrot":"orange"
]);
mapping any = ([ "1":"a string", 1:"an int", 1.0:"a float" ]);
mapping[mixed] = mixed;
mapping->string = mixed;
food_color->Raspberry = "pink";
write("Known foods:\n");
foreach(food_color; string food; )
{
write(food+"\n");
}
if(!zero_type(mapping->index))
{
}
else
{
}
foreach( ({ "Banana", "Milk" }) ;; string name)
{
if(!zero_type(food_color[name]))
write("%s is a food.\n", name);
else
write("%s is a drink.\n", name);
}
mapping age = ([ "Toddler":3,
"Unborn":0,
"Newborn":0.0,
"Phantasm":UNDEFINED ]);
foreach( ({ "Toddler", "Unborn", "Newborn", "Phantasm", "Relic" });; string thing)
{
write(thing+":");
if(!zero_type(age[thing]))
write(" Exists");
if(age[thing])
write(" True");
write("\n");
}
class Nil
{
int `!() {return 1;}
string _sprintf() {return "Nil";}
int defined(mixed var)
{
return !zero_type(var) && var!=this;
}
}
Nil NIL = Nil();
function defined = NIL->defined;
mapping age = ([ "Toddler":3,
"Unborn":0,
"Phantasm":NIL ]);
foreach( ({ "Toddler", "Unborn", "Phantasm", "Relic" });; string thing)
{
write(thing+":");
if(!zero_type(age[thing]))
write(" Exists");
if(defined(age[thing]))
write(" Defined");
if(age[thing])
write(" True");
write("\n");
}
mapping size = ([]);
string filename;
while(filename = Stdio.stdin->gets())
{
filename -= "\n";
if(size[filename])
continue;
if(!zero_type(size[filename]))
continue
object stat = file_stat(filename)
if(stat)
size[filename] = stat->size;
else
size[filename] = -1;
}
void print_foods()
{
write("Foods:%{ %s%}\n", indices(food_color));
write("Values: ");
foreach(food_color; string food; string color)
{
if(color)
write(color+" ");
else
write("(no value) ");
}
write("\n");
}
write("Initially:\n");
print_foods();
write("\nWith Banana set to 0\n");
food_color->Banana = 0;
print_foods();
write("\nWith Banana deleted\n");
food_color -= ([ "Banana":"the value is irrelevant" ]);
print_foods();
food_color -= ([ "Banana":0, "Apple":0, "Cabbage":0 ]);
m_delete(food_color, "Banana");
foreach( mapping; type index; type value)
{
}
foreach(food_color; string food; string color)
{
write("%s is %s.\n", food, color);
}
foreach(sort(indices(food_color));; string food)
{
write("%s is %s.\n", food, food_color[food]);
}
void main(int argc, array argv)
{
object file;
mapping from = ([]);
if(sizeof(argv)>1)
file = Stdio.File(argv[1], "r");
else
file = Stdio.stdin;
foreach(file; int count; string line)
{
array email = array_sscanf(line, "From: %s");
if(sizeof(email))
from[email[0]]++;
}
write("end\n");
foreach(sort(indices(from));; string person)
{
write("%s: %d\n", person, from[person]);
}
}
write("%O\n", food_color);
foreach(food_color; string food; string color)
{
write("%s is %s\n", food, color);
}
write("%{%s is %s\n%}", sort((array)food_color));
mapping(string:array(string)) ttys = ([]);
object pipe = Stdio.File();
Process.create_process(({ "who" }), ([ "stdout":pipe->pipe() ]));
foreach(pipe->line_iterator();; string line)
{
array tty=(line/" ")-({ "" });
if(!ttys[tty[0]])
ttys[tty[0]] = ({ tty[1] });
else
ttys[tty[0]] += ({ tty[1] });
}
foreach(sort(indices(ttys));; string user)
{
write("%s: %{%s %}\n", user, ttys[user]);
}
foreach(sort(indices(ttys));; string user)
{
write("%s: %d ttys.\n", user, sizeof(ttys[user]));
foreach(ttys[user];; string tty)
{
object stat = file_stat("/dev/"+tty);
string user;
if(stat)
user = getpwuid(stat->uid)[0];
else
user = "(not available)";
write("\t%s (owned by %s)\n", tty, user);
}
}
mapping multihash_delete(mapping hash, mixed key, mixed value)
{
if(arrayp(hash[key]))
hash[key]-=({ value });
if(!sizeof(hash[key]))
m_delete(hash, key);
return hash;
}
mapping lookup;
mixed value;
mixed key = search(lookup, value);
mapping lookup;
mapping reverse = mkmapping(values(lookup), indices(lookup));
mapping surname = ([ "Mickey":"Mantle", "Babe":"Ruth" ]);
write("%s\n", search(surname, "Mantle"));
mapping first_name = mkmapping(values(surname), indices(surname));
write("%s\n", first_name->Mantle);
void main(int argc, array(string) argv)
{
if(argc < 2)
{
write("usage: foodfind food_or_color\n");
}
string given = argv[1];
mapping color = ([ "Apple":"red",
"Banana":"yellow",
"Lemon":"yellow",
"Carrot":"orange"
]);
if(color[given])
write("%s is a food with color %s\n", given, color[given]);
string food = search(color, given);
if(food)
write("%s is a food with color %s\n", food, given);
array foods = ({ search(color, given) });
food = 0;
while(food = search(color, given, foods[-1]))
{
foods += ({ food });
}
write("%{%s %}were %s foods.\n", foods, given);
}
mapping foods_with_color = ([]);
foreach(food_color; string food; string color)
{
if(!foods_with_color[color])
foods_with_color[color] = ({ food });
else
foods_with_color[color] += ({ food });
}
write("%{%s %}were yellow foods.\n", foods_with_color->yellow);
mapping hash;
foreach(sort(indices(hash));; mixed key)
{
mixed value = hash[key];
}
foreach(sort(indices(food_color));; string food)
{
write("%s is %s.\n", food, food_color[food]);
}
array foods = indices(food_color);
sort(sizeof(values(food_color)[*]), foods);
foreach(foods;; string food)
{
write("%s is %s.\n", food, food_color[food]);
}
mapping A, B;
mapping merged = A + B;
mapping merged = A | B;
mapping drink_color = ([ "Milk":"white",
"Tomato juice":"red" ]);
mapping ingested_color = drink_color + food_color;
mapping both = A & B;
mapping one = A ^ B;
mapping exA = A - B;
mapping citrus_color = ([ "Lemon":"yellow",
"Orange":"orange",
"Lime":"green"
]);
array non_citrus = indices(food_color - citrus_color);
array a = ({ 1,2 });
array b = ({ 1,2 });
mapping m = ([ a:"a" ]);
m[b];
m[b]="b";
m;
mapping count = ([]);
foreach(ARRAY;; mixed element)
{
count[element]++;
}
mapping father = ([ "Cain":"Adam",
"Abel":"Adam",
"Seth":"Adam",
"Enoch":"Cain",
"Irad":"Enoch",
"Mehujael":"Irad",
"Methusael":"Mehujael",
"Lamech":"Methusael",
"Jabal":"Lamech",
"Jubal":"Lamech",
"Tubalcain":"Lamech",
"Enos":"Seth"
]);
foreach(Stdio.stdin;; string name)
{
do
{
write("%s ", name);
} while(name = father[name]);
write("\n");
}
mapping children = ([]);
foreach(father; string k; string v)
{
if(!children[v])
children[v] = ({ k });
else
children[v] += ({ k });
}
foreach(Stdio.stdin;; string name)
{
write("%s begat %s.\n", name, (children[name]||({ "nobody" }))*", ");
}
mapping includes = ([]);
foreach(files, string file)
{
string F = Stdio.read_file(file);
if(!F)
werror("Couldn't read %s; skipping.\n", file);
foreach(F/"\n";; string line)
{
array included = array_sscanf(line, "%*[ \t]#include%*[ \t]%*[<\"]%s%*[>\"]%*[ \t]");
if(sizeof(included))
{
if(!includes[included[0]])
includes[included[0]] = ({ file });
else
includes[included[0]] += ({ file });
}
}
}
array uniq = `|( @values(includes) );
array include_free = sort( uniq - indices(includes) );
array input(array(string) args)
{
mapping Dirsize=([]);
mapping Kids=([]);
object pipe = Stdio.File();
Process.create_process(({ "du" })+args, ([ "stdout":pipe->pipe() ]));
string name;
foreach(pipe->line_iterator();; string line)
{
int size;
[size, name] = array_sscanf(line, "%d%*[ \t]%s");
Dirsize[name] = size;
array path = name/"/";
string parent = path[..sizeof(path)-2]*"/";
if(!Kids[parent])
Kids[parent] = ({ name });
else
Kids[parent] += ({ name });
}
return ({ name, Dirsize, Kids });
}
void getdots(string root, mapping Dirsize, mapping Kids)
{
int size, cursize;
size = cursize = Dirsize[root];
if(Kids[root])
{
foreach(Kids[root];; string kid)
{
cursize -= Dirsize[kid];
getdots(kid, Dirsize, Kids);
}
}
else
Kids[root] = ({});
if(size != cursize)
{
string dot = root+"/.";
Dirsize[dot] = cursize;
Kids[root] += ({ dot });
}
}
void output(string root, mapping Dirsize, mapping Kids,
int width, void|string prefix)
{
if(!prefix)
prefix="";
string path = (root/"/")[-1];
int size = Dirsize[root];
write("%*d %s%s\n", width, size, prefix, path);
prefix += "|" + " "*(sizeof(path)-1);
if(Kids[root])
{
array kids = Kids[root];
sort(Dirsize[kids[*]], kids);
output(kids[*], Dirsize, Kids, width, prefix);
}
}
void main(int argc, array(string) argv)
{
mapping Dirsize;
mapping Kids;
string topdir;
[ topdir, Dirsize, Kids ] = input(argv[1..]);
getdots(topdir, Dirsize, Kids);
output(topdir, Dirsize, Kids, sizeof((string)sort(values(Dirsize))[-1]));
}
dst = Regexp("this")->replace(src, "that");
dst = Regexp("this")->replace(src, "that");
dst = Regexp("^.*/")->replace(argv[0], "");
string capword = Regexp("[a-z]+")->replace
("foo.bar",
lambda (string c) {
c[0] = upper_case(c[0]);
return c;
} );
string INPUT = Stdio.read_file("/usr/local/widgets/data");
if(!INPUT)
{
werror("Couldn't open /usr/local/widgets/data for reading\n");
exit(1);
}
foreach(INPUT/"\n";; string line)
{
if(search(line, "blue")!=-1)
write(line+"\n");
}
Stdio.File INPUT = Stdio.File("/usr/local/widgets/data", "r");
if(!INPUT)
{
werror("Couldn't open /usr/local/widgets/data for reading\n");
exit(1);
}
foreach(INPUT->line_iterator();; string line)
{
if(search(line, "blue")!=-1)
write(line+"\n");
}
INPUT->close();
foreach(Stdio.stdin;; string line)
{
if(!sizeof(array_sscanf(line, "%*s%d")))
werror("No digit found.\n");
write("Read: %s\n", line);
}
Stdio.stdout->close() || werror("couldn't close STDOUT\n") && exit(1);
Stdio.File logfile = Stdio.File("/tmp/log", "w");
object LOGFILE = logfile->line_iterator();
do
{
string line=LOGFILE->value();
}
while(LOGFILE->next())
logfile->close();
function write = logfile->write;
write("Countdown initiated ...\n");
write = Stdio.stdout->write;
write("You have 30 seconds to reach minimum safety distance.\n");
string path;
string file = Stdio.read_file(path);
Stdio.File file = Stdio.File(path, "r");
Stdio.write_file(path, "content");
Stdio.File file = Stdio.File(path, "wc");
Stdio.write_file(path, "content", 0600);
Stdio.File file = Stdio.File(path, "wc", 0600);
if(!file_stat(path))
Stdio.write_file(path, "content");
Stdio.File file = Stdio.File(path, "wcx");
if(!file_stat(path))
Stdio.write_file(path, "content", 0600);
Stdio.File file = Stdio.File(path, "wcx", 0600);
Stdio.append_file(path, "content");
Stdio.File file = Stdio.File(path, "wac");
Stdio.append_file(path, "content", 0600);
Stdio.File file = Stdio.File(path, "wac", 0600);
Stdio.File file = Stdio.File(path, "wacx");
string file = Stdio.read_file(path);
string updated = file+"foo"
Stdio.write_file(path, updated);
Stdio.File file = Stdio.File(path);
Stdio.File file = Stdio.File(path, "rwcx");
string filename;
if(filename[0] == "~")
{
string user, path, home;
[ user, path ] = array_sscanf(filename, "~%[^/]%s");
if(user == "")
home = getenv("HOME") || getenv("LOGDIR") || getpwuid(geteuid())[5];
else
home = getpwnam(user)[5];
filename = home+path;
}
string path = "/tmp/fooo";
mixed error = catch
{
Stdio.File file = Stdio.File(path, "r");
};
if(error)
{
werror("Couldn't open %s for reading:\n", path);
werror(error[0]);
}
Stdio.File fh;
string name;
do
{
name = "/tmp/"+MIME.encode_base64(random_string(10));
fh = Stdio.File(name, "rwcx");
}
while(!fh)
atexit(lambda(){ fh->close(); rm(name); });
fh = Stdio.FakeFile();
string data = "your data goes here";
string data = #"your data goes here
and here
and ends here";
object stat = file_stat(__FILE__);
int raw_time = stat->ctime;
int size = stat->size;
int kilosize = size/1024;
write("<P>Script size is %dk\n", kilosize);
write("<P>Last script update: %s\n", Calendar.Second(raw_time)->format_nicez());
int main(int argc, array(string) argv) {
int count=0;
object f = Stdio.FILE(argv[1]);
foreach(f->line_iterator(f); int number; string paragraph) {
count++;
}
write("number of paragraphs= "+count+"\n");
return 0;
}
Stdio.Stat entry;
entry = file_stat("/bin/vi");
entry = file_stat("/usr/bin");
entry = file_stat(argv[1]);
Stdio.Stat entry; int ctime, size;
entry = file_stat("/bin/vi");
ctime = entry->ctime;
size = entry->size;
int(0..1) containsText(Stdio.File file)
{
string c;
while ((c = file->read(1)) != NULL) { (c == NEWLINE) && return 1; }
return 0;
}
int(0..1) containsText(Stdio.FILE file)
{
int c;
while ((c = file->getchar()) != EOF) { (c == LF) && return 1; }
return 0;
}
int(0..1) isTextFile(string filename)
{
return chop(Process.popen("file -bN " + filename), 1) == "ASCII text";
}
containsText(Stdio.File(argv[1])) || write("File %s doesn't have any text in it\n", argv[1]);
isTextFile(argv[1]) || write("File %s doesn't have any text in it\n", argv[1]);
Filesystem.Traversion dirtree = Filesystem.Traversion("/usr/bin");
foreach(dirtree; string dir; string file)
{
write("Inside %s is something called %s\n", chop(dir, 1), file);
}
string filename = "example.txt";
Stdio.Stat fs = file_stat(filename);
int readtime = fs->atime, writetime = fs->mtime;
System.utime(filename, readtime, writetime);
constant SECONDS_PER_DAY = 60 * 60 * 24;
string filename = "example.txt";
Stdio.Stat fs = file_stat(filename);
int atime = fs->atime, mtime = fs->mtime;
atime -= 7 * SECONDS_PER_DAY; mtime -= 7 * SECONDS_PER_DAY;
System.utime(filename, atime, mtime);
argc != 1 || die("usage: " + argv[0] + " filename");
Stdio.Stat fs = file_stat(argv[1]);
int atime = fs->atime, mtime = fs->mtime;
Process.system(getenv("EDITOR") || "vi" + " " + argv[1]);
mixed result = catch { System.utime(argv[1], atime, mtime); };
(result == OK) || write("Error updating timestamp on file, %s!\n", argv[1]);
string filename = "...";
rm(filename) || write("Can't delete, %s!\n", filename);
int(0..1) rmAll(array(string) filelist)
{
mixed result = catch
{
foreach(filelist, string filename) { rm(filename) || throw(PROBLEM); }
};
return result == OK;
}
array(string) filelist = ({"/tmp/x", "/tmp/y", "/tmp/z"});
rmAll(filelist) || write("Can't delete all files in array!\n");
void die(string msg, void|int(1..256) rc) { werror(msg + NEWLINE); exit(rc ? rc : PROBLEM); }
string filename = "...";
rm(filename) || die("Can't delete " + filename);
array(string) filelist = ({"/tmp/x", "/tmp/y", "/tmp/z"});
int deleted, count = sizeof(filelist);
foreach(filelist, string filename) { rm(filename) && ++deleted; }
(deleted == count) || write("Could only delete %d of %d files\n", deleted, count);
string oldfile = "/tmp/old", newfile = "/tmp/new";
Stdio.cp(oldfile, newfile) || write("Error copying file\n");
string oldfile = "/tmp/old", newfile = "/tmp/new";
mixed result = catch { Stdio.write_file(newfile, Stdio.read_file(oldfile)); };
(result == OK) || write("Problem copying file %s to file %s\n", oldfile, newfile);
int system(string cmd)
{
Stdio.File fout = Stdio.File(), ferr = Stdio.File();
Stdio.File pout = fout->pipe(Stdio.PROP_IPC),
perr = ferr->pipe(Stdio.PROP_IPC);
int rc = Process.spawn(cmd, 0, pout, perr)->wait();
pout->close(); destruct(pout); fout->close(); destruct(fout);
perr->close(); destruct(perr); ferr->close(); destruct(ferr);
return rc;
}
int(0..1) unixFileCopy(string oldfile, string newfile)
{
string cmd = "cp --force --reply=yes " + oldfile + " " + newfile;
return system(cmd) == OK;
}
int(0..1) vmsFileCopy(string oldfile, string newfile)
{
string cmd = "copy " + oldfile + " " + newfile;
return system(cmd) == OK;
}
string oldfile = "/tmp/old", newfile = "/tmp/new";
unixFileCopy(oldfile, newfile) || write("Problem copying file %s to file %s\n", oldfile, newfile);
string oldfile = "/tmp/old", newfile = "/tmp/new";
mv(oldfile, newfile) || write("Problem moving / renaming file %s to file %s\n", oldfile, newfile);
mapping(array(int):int) seen = ([]);
void do_my_thing(string filename)
{
Stdio.Stat fs = file_stat(filename);
array(int) arr = aggregate(fs->inode, fs->dev);
(seen[arr] && (seen[arr] += 1)) || (seen[arr] = 1);
}
constant SEP = ":"; mapping(array(int):string) seen = ([]);
array(string) files = ({"f1.txt", "f2.txt", "f3.txt"});
foreach(files, string filename)
{
Stdio.Stat fs = file_stat(filename);
array(int) arr = aggregate(fs->inode, fs->dev);
(seen[arr] && (seen[arr] += (SEP + filename))) || (seen[arr] = filename);
}
array(array(int)) idxarr = indices(seen); sort(idxarr);
foreach(idxarr, array(int) inodev)
{
foreach(seen[inodev] / SEP, string filename)
{
write("%s\n", filename);
}
}
string dirname = "..."; array(string) DIR = get_dir(dirname);
foreach(DIR, string filename)
{
string path = dirname + "/" + filename;
}
string dirname = "/usr/local/bin"; int|array(string) DIR = get_dir(dirname);
DIR || die("Can't open " + dirname);
write("Text files in %s are:\n", dirname);
foreach(DIR, string filename)
{
string path = dirname + "/" + filename;
isTextFile(path) && write("%s\n", filename);
}
array(string) plain_files(string dirname)
{
function fp =
lambda(string filename, string dirname)
{
return !has_prefix(filename, ".") && isTextFile(dirname + "/" + filename);
};
function mp =
lambda(string filename, string dirname)
{
return dirname + "/" + filename;
};
array(string) paths = map(filter(get_dir(dirname), fp, dirname), mp, dirname);
sort(paths);
return paths;
}
int(0..1)|array(string) grep(string regexp, string|array(string) arr)
{
if (stringp(arr)) return Regexp.match(regexp, arr);
if (arrayp(arr))
{
function fp =
lambda(string filename, string regexp)
{
return Regexp.match(regexp, filename);
};
return filter(arr, fp, regexp);
}
return 0;
}
string dirname = "...";
int|array(string) filenames = glob("*.c", get_dir(dirname));
string dirname = "...";
int|array(string) filenames = grep("\.c$", get_dir(dirname));
string dirname = "...";
int|array(string) filenames = grep("\.[CHch]$", get_dir(dirname));
string dirname = "...";
int|array(string) dir = get_dir(dirname);
dir || die("Couldn't open " + dirname + " for reading");
mapping(int:string) files = ([]); int idx = -1; string path;
foreach(dir, string file)
{
if (!grep("\.[CHch]$", file)) continue;
path = dirname + "/" + file;
isTextFile(path) && (files[++idx] = path);
}
void|mixed process_directory(string path, function(string, mixed ... : void|mixed) op, mixed ... extra_args)
{
Stdio.Stat file = file_stat(path, 1); if (!file) return 0;
if (file->isdir)
if (array(string) files = get_dir(path))
foreach(files, string file)
process_directory(path + "/" + file, op, @extra_args);
return op(path, @extra_args);
}
array(string) dirlist = ({ "/tmp/d1", "/tmp/d2", "/tmp/d3" });
foreach(dirlist, string dir)
{
}
array(string) dirlist = ({ "/tmp/d1", "/tmp/d2", "/tmp/d3" });
function pf =
lambda(string path)
{
write("%s\n", path);
};
foreach(dirlist, string dir)
{
int|array(string) filelist = get_dir(dir);
if (!filelist) { write("%s does not exist\n", dir); continue; }
if (sizeof(filelist) == 0) { write("%s is empty\n", dir); continue; }
foreach(filelist, string filename)
{
pf(dir + "/" + filename);
}
}
array(string) dirlist = ({ "/tmp/d1", "/tmp/d2", "/tmp/d3" });
function pf =
lambda(string path)
{
write("%s\n", path);
};
foreach(dirlist, string dir)
{
process_directory(dir, pf);
}
void accum_filesize(string path, array(int) accum)
{
int|Stdio.Stat fs = file_stat(path);
(fs && fs->isreg) && (accum[0] += fs->size);
}
argc == 2 || die("usage: " + argv[0] + " dir");
Stdio.Stat fs; string dir = argv[1];
((fs = file_stat(dir)) && fs->isdir) || die(dir + " does not exist / not a directory");
array(int) dirsize = ({0});
process_directory(dir, accum_filesize, dirsize);
write("%s contains %d bytes\n", dir, dirsize[0]);
void biggest_file(string path, array(mixed) biggest)
{
int|Stdio.Stat fs = file_stat(path);
if (fs && fs->isreg && biggest[1] < fs->size)
{
biggest[0] = path; biggest[1] = fs->size;
}
}
argc == 2 || die("usage: " + argv[0] + " dir");
Stdio.Stat fs; string dir = argv[1];
((fs = file_stat(dir)) && fs->isdir) || die(dir + " does not exist / not a directory");
array(mixed) biggest = ({"", 0});
process_directory(dir, biggest_file, biggest);
write("Biggest file is %s containing %d bytes\n", biggest[0], biggest[1]);
void youngest_file(string path, array(mixed) youngest)
{
int|Stdio.Stat fs = file_stat(path);
if (fs && fs->isreg && youngest[1] > fs->ctime)
{
youngest[0] = path; youngest[1] = fs->ctime;
}
}
argc == 2 || die("usage: " + argv[0] + " dir");
Stdio.Stat fs; string dir = argv[1];
((fs = file_stat(dir)) && fs->isdir) || die(dir + " does not exist / not a directory");
array(mixed) youngest = ({"", Int.NATIVE_MAX});
process_directory(dir, youngest_file, youngest);
write("Youngest file is %s dating %s\n", youngest[0], ctime(youngest[1]));
void print_name_if_dir(string path)
{
int|Stdio.Stat fs = file_stat(path);
if (fs && fs->isdir) write("%s\n", path);
}
argc == 2 || die("usage: " + argv[0] + " dir");
Stdio.Stat fs; string dir = argv[1];
((fs = file_stat(dir)) && fs->isdir) || die(dir + " does not exist / not a directory");
process_directory(dir, print_name_if_dir);
int(0..1) rmTree(string dirname) { return Stdio.recursive_rm(dirname); }
string dirtree = "/tmp/dirtree";
rmTree(dirtree) || write("Problem removing directory tree %s\n", dirtree);
int(0..1) rmTree(string dirname) { return process_directory(dirname, rm); }
string dirtree = "/tmp/dirtree";
rmTree(dirtree) || write("Problem removing directory tree %s\n", dirtree);
array(string) names = ({"f1.txt", "f2.txt", "f3.txt"});
function rename = lambda(string name) { return replace(name, ".txt", ".text"); };
foreach(names, string name)
{
string newname = rename(name);
mv(name, newname) || write("Could not rename %s to %s\n", name, newname);
}
argc > 2 || die("usage: " + argv[0] + " expr repl files...");
string expr = argv[1], repl = argv[2];
foreach(argv[3..], string name)
{
string newname = Regexp.replace(expr, name, repl);
if (!equal(name, newname))
mv(name, newname) || write("Could not rename %s to %s\n", name, newname);
}
string file_extension(string filename, void|string separator)
{
return (filename / (separator || "."))[-1];
}
mapping(string:string) file_parse(string path)
{
return
mkmapping(({"dirname", "basename", "extension"}),
({dirname(path), basename(path), file_extension(basename(path))}));
}
string path = "/tmp/dirtree/s/s1/s1.txt";
string dir = dirname(path);
string base = basename(path);
mapping(string:string) pm = file_parse(path);
write("%s\n", pm["dirname"]);
write("%s\n", pm["basename"]);
write("%s\n", pm["extension"]);
string path = "/usr/lib/libc.a";
string dir = dirname(path);
string base = basename(path);
write("dir is %s, file is %s\n", dir, base);
string path = "/usr/lib/libc.a";
mapping(string:string) pm = file_parse(path);
write("dir is %s, name is %s, extension is %s\n",
pm["dirname"], pm["basename"], "." + pm["extension"]);
string path = "Hard%20Drive:System%20Folder:README.txt";
mapping(string:string)
pm = mkmapping(({"drive", "folder", "filename"}),
replace(path, "%20", " ") / ":"),
fm = mkmapping(({"name", "extension"}),
pm["filename"] / ".");
write("dir is %s, name is %s, extension is %s\n",
pm["drive"] + ":" + pm["folder"],
fm["name"], "." + fm["extension"]);
@@INCOMPLETE@@
@@INCOMPLETE@@
@@INCOMPLETE@@
@@INCOMPLETE@@
int greeted;
void hello()
{
write("hi there!, this procedure has been called %d times\n", ++greeted);
}
int how_many_greetings()
{
return greeted;
}
int main()
{
hello();
int greetings = how_many_greetings();
write("bye there!, there have been %d greetings so far\n", greetings);
}
int greeted;
function hello = lambda()
{
write("hi there!, this procedure has been called %d times\n", ++greeted);
};
function how_many_greetings = lambda() { return greeted; };
int main()
{
hello();
int greetings = how_many_greetings();
write("bye there!, there have been %d greetings so far\n", greetings);
}
float hypotenuse(float side1, float side2)
{
return side1 * side1 + side2 * side2;
}
float diag = hypotenuse(3.0, 4.0);
float hypotenuse(int|float side1, int|float side2)
{
float s1 = intp(side1) ? (float) side1 : side1;
float s2 = intp(side2) ? (float) side2 : side2;
return s1 * s1 + s2 * s2;
}
float diag = hypotenuse(3.0, 4.0);
float diag = hypotenuse(3, 4);
float hypotenuse(mixed side1, mixed side2)
{
if (stringp(side1)) { ... }
if (arrayp(side1)) { ... }
if (objectp(side1)) { ... }
...
}
float diag = hypotenuse(3.0, 4.0);
float diag = hypotenuse(3, 4);
float diag = hypotenuse("3", "4");
float diag = hypotenuse(({3}), ({4}));
float hypotenuse(float side1, mixed side2, mixed ... args)
{
... side1 ... side2 ...
int total_passed_args = query_num_arg();
int optional_args = sizeof(args);
foreach(args, mixed arg)
{
... if (strinp(arg)) { ... }
}
...
}
float diag = hypotenuse(3.0, 4.0);
float diag = hypotenuse(3.0, 4.0, "a");
float diag = hypotenuse(3.0, 4.0, lambda(){ return 5; }, "fff");
float diag = hypotenuse(3.0, 4.0, 1, "x", ({ 6, 7, 9 }));
array(int|float) int_all(array(int|float) arr)
{
array(int|float) retarr = copy_value(arr);
int i; for(int i; i < sizeof(retarr); ++i) { retarr[i] = (int) arr[i]; }
return retarr;
}
array(int|float) trunc_all(array(int|float) arr)
{
int i; for(int i; i < sizeof(arr); ++i) { arr[i] = (int) arr[i]; }
return arr;
}
array(int|float) nums = ({1.4, 3.5, 6.7});
array(int|float) ints = int_all(nums);
write("%O\n", nums);
write("%O\n", ints);
ints = trunc_all(nums);
write("%O\n", nums);
write("%O\n", ints);
void some_func()
{
mixed variable = something;
}
string name = argv[1]; int age = (int) argv[2];
int c = fetch_time();
int condition;
int run_check()
{
...
condition = 1;
}
int check_x(int x)
{
string y = "whatever";
run_check();
if (condition) write("got x: %d\n", x);
}
class Counter
{
private int counter;
static void create(int start) { counter = start; }
public int next() { return ++counter; }
public int prev() { return --counter; }
}
int main()
{
Counter counter = Counter(42);
write("%d\n", counter->next());
write("%d\n", counter->prev());
}
class Static
{
int counter;
class Counter
{
public int next() { return ++counter; }
public int prev() { return --counter; }
}
Counter make() { return Counter(); }
public void create(int counter_) { counter = counter_; }
}
int main()
{
Static mkst = Static(42);
Static.Counter counter_1 = mkst->make();
Static.Counter counter_2 = mkst->make();
write("%d\n", counter_1->next());
write("%d\n", counter_1->next());
write("%d\n", counter_2->next());
write("%d\n", counter_2->prev());
}
function(string : function(void : int)) make_counter(int start)
{
int counter = start;
int next_counter() { return ++counter; };
int prev_counter() { return --counter; };
return
lambda(string op)
{
if (op == "next") return next_counter;
if (op == "prev") return prev_counter;
return 0;
};
}
int next_counter(function(string : function(void : int)) counter)
{
return counter("next")();
}
int prev_counter(function(string : function(void : int)) counter)
{
return counter("prev")();
}
int main()
{
function(string : function(void : int)) counter = make_counter(42);
write("%d\n", next_counter(counter));
write("%d\n", prev_counter(counter));
}
int|array(int) array_diff(array(int) a, array(int) b)
{
int|array(int) ret = sizeof(a) != sizeof(b) ? 0 : copy_value(a);
if (!ret) ret;
for (int i; i < sizeof(ret); ++i) { ret[i] -= b[i]; }; return ret;
}
int|array(int) add_vec_pair(array(int) a, array(int) b)
{
int vecsize = sizeof(a);
int|array(int) ret = vecsize != sizeof(b) ? 0 : allocate(vecsize);
if (!ret) ret;
for (int i; i < vecsize; ++i) { ret[i] = a[i] + b[i]; }; return ret;
}
array(int) a = ({1, 2}), b = ({5, 8});
array(int) c = add_vec_pair(a, b);
write("%O\n", c);
int|array(int)|string mysub()
{
...
return 5;
...
return ({5});
...
return "5";
}
int|array(int)|string receiver = mysub();
if (intp(receiver)) { ... }
if (arrayp(receiver)) { ... }
if (stringp(receiver)) { ... }
...
mixed mysub()
{
...
return 5;
...
return ({5});
...
return "5";
}
mixed receiver = mysub();
if (intp(receiver)) { ... }
if (arrayp(receiver)) { ... }
if (stringp(receiver)) { ... }
...
class KeyedValue
{
string key; mixed value;
static void create(string key_, mixed value_)
{
key = key_; value = value_;
}
}
void the_func(array(KeyedValue) keyargs)
{
foreach(keyargs, KeyedValue kv)
{
write("Key: %10s|Value: %10O\n", kv->key, kv->value);
}
}
int main()
{
array(KeyedValue) keyargs =
aggregate(KeyedValue("name", "Bob"),
KeyedValue("age", 36),
KeyedValue("income", 51000));
the_func(keyargs);
}
class RaceTime
{
int time; string dim;
static void create(int time_, string dim_)
{
time = time_; dim = dim_;
}
}
void the_func(mapping(string : RaceTime) ... args)
{
int start_time, finish_time, increment_time;
string start_dim, finish_dim, increment_dim;
foreach(args, mapping(string : RaceTime) arg)
{
arg["start"] && (start_time = arg["start"]->time, start_dim = arg["start"]->dim);
arg["finish"] && (finish_time = arg["finish"]->time, finish_dim = arg["finish"]->dim);
arg["increment"] && (increment_time = arg["increment"]->time, increment_dim = arg["increment"]->dim);
}
write("times: start %d, finish %d, increment %d\n",
start_time, finish_time, increment_time);
}
int main()
{
array(mapping(string : RaceTime)) named_args =
({
(["increment" : RaceTime(20, "s")]),
(["start" : RaceTime(5, "m")]),
(["finish" : RaceTime(3, "m")]) });
the_func(@named_args);
named_args =
({
(["start" : RaceTime(5, "m")]),
(["finish" : RaceTime(30, "m")]) });
the_func(@named_args);
the_func((["finish" : RaceTime(30, "m")]));
}
array(mixed) somefunc()
{
array(int) arr = ({1, 2, 3});
mapping(string : int) hash = (["x" : 1, "y" : 2, "z" : 3]);
return aggregate(arr, hash);
}
array(mixed) arr = somefunc();
foreach(arr, mixed item)
{
write("Return item has type: %t, value: %O\n", item, item);
}
class RetValues
{
array(int) arr; mapping(string : int) hash;
static void create()
{
arr = aggregate(1, 2, 3);
hash = aggregate_mapping("x", 1, "y", 2, "z", 3);
}
}
RetValues somefunc() { return RetValues(); }
RetValues rv = RetValues();
write("Return item has type: %t, value: %O\n", rv->arr, rv->arr);
write("Return item has type: %t, value: %O\n", rv->hash, rv->hash);
void die(string msg, void|int(1..256) rc) { werror(msg + NEWLINE); exit(rc ? rc : PROBLEM); }
int|array(string) afunc()
{
...
if (ok)
else
return 0;
}
int main()
{
int|array(string) arr = afunc();
if (!arr) die("Error with 'afunc' ...");
}
void func_with_no_arg() { ... }
void func_with_one_arg(int arg1) { ... }
void func_with_two_arg(int arg1, string arg2) { ... }
void func_with_three_arg(int arg1, string arg2, float arg3) { ...}
function f = lambda(int arg1 : void) { ... }
function g = lambda(int arg1) { ... }
void die(string msg, void|int(1..256) rc) { werror(msg + NEWLINE); exit(rc ? rc : PROBLEM); }
die("some message");
int(0..1) rmAll(array(string) filelist)
{
mixed result = catch
{
foreach(filelist, string filename) { rm(filename) || throw(PROBLEM); }
};
return result == OK;
}
array(string) files = ({"...", "...", "..."});
rmAll(files) || die("Could not remove all files - exiting");
int age = 18;
void print_age()
{
write("Age is %d\n", age);
}
int main()
{
int age = 5;
print_age();
age = 23;
print_age();
}
int age = 18;
void print_age()
{
write("Age is %d\n", age);
}
int main()
{
age = 5;
print_age();
age = 23;
print_age();
}
int age = 18;
void print_age()
{
write("Age is %d\n", age);
}
int main()
{
int age = global::age;
print_age();
global::age = 23;
print_age();
global::age = age;
print_age();
}
void grow() { write("grow\n"); }
void shrink() { write("shrink\n"); }
grow(); shrink();
function grow = shrink;
grow(); shrink();
function(void : void) grow = lambda() { write("grow\n"); }
function(void : void) shrink = lambda() { write("shrink\n"); }
grow(); shrink();
grow = shrink;
grow(); shrink();
function barney = lambda() { ... };
function fred = barney;
function red = lambda(string text)
{
return "<FONT COLOR='red'>" + text + "</FONT>";
};
write("%s\n", red("careful here"));
function colour_font = lambda(string colour, string text)
{
return "<FONT COLOR='" + colour + "'>" + text + "</FONT>";
};
function red = lambda(string text) { return colour_font("red", text); };
function green = lambda(string text) { return colour_font("green", text); };
write("%s\n", red("careful here"));
write("%s\n", green("careful there"));
string build_colour_func(string colour)
{
string bodytext = "\"<FONT COLOR='" + colour + "'>\" + text + \"</FONT>\"";
return "string " + colour + "(string text) { return " + bodytext + "; };";
}
int main(int argc, array(string) argv)
{
array(string) colours =
({"red", "blue", "green", "yellow", "orange", "purple", "violet"});
string cf_text = "";
foreach(colours, string colour)
{
cf_text += build_colour_func(colour);
}
object cf_code = compile_string(cf_text)();
mapping(string:string) colours_and_text =
(["red":"baron", "blue":"zephyr", "green":"beret",
"yellow":"ribbon", "orange":"county", "purple":"haze",
"violet":"temper"]);
foreach(indices(colours_and_text), string colour)
{
function colour_func = cf_code[colour];
write("%s\n", colour_func(colours_and_text[colour]));
}
}
mapping functions = ([]);
function `->(string fun)
{
if(!functions->fun)
functions[fun]=lambda(mixed|void ... args)
{
return sprintf("<FONT COLOR=%s>%{%s %}</FONT>", fun, args);
};
return functions[fun];
}
write(object_of_your_class->chartreuse("stuff"));
int outer(int arg)
{
int x = arg + 35;
int inner() { return x * 19; };
return x + inner();
}
int outer(int arg)
{
int x = arg + 35;
function(void : int) inner = lambda() { return x * 19; };
return x + inner();
}
function outer = lambda(int arg)
{
int x = arg + 35;
return (lambda() { return x * 19; })() + x;
};
function(int : int) outer = lambda(int arg)
{
int x = arg + 35;
return (lambda() { return x * 19; })() + x;
};
@@INCOMPLETE@@
@@INCOMPLETE@@
[string host,array ip,array alias] = gethostbyname("www.example.com");
Stdio.File sock=Stdio.File();
if (!sock->connect(remote_host,remote_port))
{
werror("Couldn't connect to %s:%d: %s\n",remote_host,remote_port,strerror(sock->errno()));
return 1;
}
sock->write("Hello, world!");
string answer=sock->read();
sock->close();
Stdio.Port mainsock=Stdio.Port();
if (!mainsock->bind(server_port))
{
werror("Couldn't be a tcp server on port %d: %s\n",server_port,strerror(mainsock->errno()));
return 1;
}
while (1)
{
Stdio.File sock=mainsock->accept();
if (!sock) break;
}
sock->write("What is your name?\n");
string response=sock->read(1024,1);
Stdio.FILE sock2=Stdio.FILE(); sock2->assign(sock);
string response=sock2->gets();
string other_end=sock->query_address();
sock->close("r");
sock->close("w");
sock->close("rw");
sock->close();
Stdio.Port mainsock=Stdio.Port();
if (!mainsock->bind(server_port))
{
werror("Couldn't be a tcp server on port %d: %s\n",server_port,strerror(mainsock->errno()));
return 1;
}
while (1)
{
Stdio.File sock=mainsock->accept();
if (!sock) break;
string localaddr=sock->query_address(1);
}
if (!System.chroot("/var/daemon")) werror("Unable to chroot to /var/daemon: %s\n",strerror(errno()));