[next][previous][up][top][index]
search for:

reading files

Sometimes a file will contain a single expression whose value you wish to have access to. For example, it might be a polynomial produced by another program. The function get can be used to obtain the entire contents of a file as a single string. We illustrate this here with a file whose name is expression.

i1 : get "expression"

o1 = z^6+3*x*z^4+6*y*z^4+3*x^2*z^2+12*x*y*z^2+12*y^2*z^2+x^3+6*x^2*y+12*x*y^2+8*y^3

This isn't quite what you want, because a string containing a description of a polynomial is not the same as a polynomial. We may use value to evaluate the string and produce the corresponding polynomial, after first setting up a polynomial ring to contain it.

i2 : R = ZZ/101[x,y,z]

o2 = R

o2 : PolynomialRing
i3 : f = value get "expression"

      6       4       4     2 2          2      2 2    3     2         2     3
o3 = z  + 3x*z  + 6y*z  + 3x z  + 12x*y*z  + 12y z  + x  + 6x y + 12x*y  + 8y

o3 : R
i4 : factor f

       2          3
o4 = (z  + x + 2y)

o4 : Product

Often a file will contain code written in the Macaulay 2 language. We have a file called sample with two lines of code.

i5 : << get "sample";
sample = 2^100
print sample

To load and execute that code, use load.

i6 : load "sample"
1267650600228229401496703205376

The command needs can be used to load a file only if it hasn't already been loaded.

i7 : needs "sample"

For debugging or display purposes, it is sometimes useful to be able to simulate entering the lines of a file one by one, so they appear on the screen along with prompts and output lines. We use input for this.

i8 : input "sample"

i9 : sample = 2^100

o9 = 1267650600228229401496703205376

i10 : print sample
1267650600228229401496703205376

i11 : 

There are other ways to manipulate the contents of a file with multiple lines. First, let's use peek to observe the extent of this string returned by get.

i12 : peek get "sample"

o12 = "sample = 2^100\nprint sample\n"

The resulting string has newlines in it; we can use lines to break it apart into a list of strings, with one row in each string.

i13 : lines get "sample"

o13 = {sample = 2^100, print sample}

o13 : List

We may use peek to observe the extent of these strings.

i14 : peek lines get "sample"

o14 = {"sample = 2^100","print sample"}

We could even use stack to assemble the lines of the file into a net.

i15 : stack lines get "sample"

o15 = sample = 2^100
      print sample


[next][previous][up][top][index]
search for: