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