1Text::BibTeX::Entry(3)User Contributed Perl DocumentationText::BibTeX::Entry(3)
2
3
4

NAME

6       Text::BibTeX::Entry - read and parse BibTeX files
7

SYNOPSIS

9          use Text::BibTeX::Entry;
10
11          # ...assuming that $bibfile and $newbib are both objects of class
12          # Text::BibTeX::File, opened for reading and writing (respectively):
13
14          # Entry creation/parsing methods:
15          $entry = Text::BibTeX::Entry->new();
16          $entry->read ($bibfile);
17          $entry->parse ($filename, $filehandle);
18          $entry->parse_s ($entry_text);
19
20          # or:
21          $entry = Text::BibTeX::Entry->new( $bibfile );
22          $entry = Text::BibTeX::Entry->new( $filename, $filehandle );
23          $entry = Text::BibTeX::Entry->new( $entry_text );
24
25          # Entry query methods
26          warn "error in input" unless $entry->parse_ok;
27          $metatype = $entry->metatype;
28          $type = $entry->type;
29
30          # if metatype is BTE_REGULAR or BTE_MACRODEF:
31          $key = $entry->key;                  # only for BTE_REGULAR metatype
32          $num_fields = $entry->num_fields;
33          @fieldlist = $entry->fieldlist;
34          $has_title = $entry->exists ('title');
35          $title = $entry->get ('title');
36          # or:
37          ($val1,$val2,...$valn) = $entry->get ($field1, $field2, ..., $fieldn);
38
39          # if metatype is BTE_COMMENT or BTE_PREAMBLE:
40          $value = $entry->value;
41
42          # Author name methods
43          @authors = $entry->split ('author');
44          ($first_author) = $entry->names ('author');
45
46          # Entry modification methods
47          $entry->set_type ($new_type);
48          $entry->set_key ($new_key);
49          $entry->set ('title', $new_title);
50          # or:
51          $entry->set ($field1, $val1, $field2, $val2, ..., $fieldn, $valn);
52          $entry->delete (@fields);
53          $entry->set_fieldlist (\@fieldlist);
54
55          # Entry output methods
56          $entry->write ($newbib);
57          $entry->print ($filehandle);
58          $entry_text = $entry->print_s;
59
60          # Reset internal parser state:
61          $entry = Text::BibTeX::Entry->new();
62          $entry->parse ($filename, undef);
63          $entry->parse_s (undef);
64
65          # or:
66          $entry = Text::BibTeX::Entry->new( $filename, undef );
67          $entry = Text::BibTeX::Entry->new( undef );
68
69          # Miscellaneous methods
70          $entry->warn ($entry_warning);
71          # or:
72          $entry->warn ($field_warning, $field);
73          $entry->clone;
74

DESCRIPTION

76       "Text::BibTeX::Entry" does all the real work of reading and parsing
77       BibTeX files.  (Well, actually it just provides an object-oriented Perl
78       front-end to a C library that does all that.  But that's not important
79       right now.)
80
81       BibTeX entries can be read either from "Text::BibTeX::File" objects
82       (using the "read" method), or directly from a filehandle (using the
83       "parse" method), or from a string (using "parse_s").  The first is
84       preferable, since you don't have to worry about supplying the filename,
85       and because of the extra functionality provided by the
86       "Text::BibTeX::File" class.  Currently, this means that you may specify
87       the database structure to which entries are expected to conform via the
88       "File" class.  This lets you ensure that entries follow the rules for
89       required fields and mutually constrained fields for a particular type
90       of database, and also gives you access to all the methods of the
91       structured entry class for this database structure.  See
92       Text::BibTeX::Structure for details on database structures.
93
94       Once you have the entry, you can query it or change it in a variety of
95       ways.  The query methods are "parse_ok", "type", "key", "num_fields",
96       "fieldlist", "exists", and "get".  Methods for changing the entry are
97       "set_type", "set_key", "set_fieldlist", "delete", and "set".
98
99       Finally, you can output BibTeX entries, again either to an open
100       "Text::BibTeX::File" object, a filehandle or a string.  (A filehandle
101       or "File" object must, of course, have been opened in write mode.)
102       Output to a "File" object is done with the "write" method, to a
103       filehandle via "print", and to a string with "print_s".  Using the
104       "File" class is recommended for future extensibility, although it
105       currently doesn't offer anything extra.
106

METHODS

108   Entry creation/parsing methods
109       new ([OPTS ,] [SOURCE])
110           Creates a new "Text::BibTeX::Entry" object.  If the SOURCE
111           parameter is supplied, it must be one of the following: a
112           "Text::BibTeX::File" (or descendant class) object, a
113           filename/filehandle pair, or a string.  Calls "read" to read from a
114           "Text::BibTeX::File" object, "parse" to read from a filehandle, and
115           "parse_s" to read from a string.
116
117           A filehandle can be specified as a GLOB reference, or as an
118           "IO::Handle" (or descendants) object, or as a "FileHandle" (or
119           descendants) object.  (But there's really no point in using
120           "FileHandle" objects, since "Text::BibTeX" requires Perl 5.004,
121           which always includes the "IO" modules.)  You can not pass in the
122           name of a filehandle as a string, though, because
123           "Text::BibTeX::Entry" conforms to the "use strict" pragma (which
124           disallows such symbolic references).
125
126           The corresponding filename should be supplied in order to allow for
127           accurate error messages; if you simply don't have the filename, you
128           can pass "undef" and you'll get error messages without a filename.
129           (It's probably better to rearrange your code so that the filename
130           is available, though.)
131
132           Thus, the following are equivalent to read from a file named by
133           $filename (error handling ignored):
134
135              # good ol' fashioned filehandle and GLOB ref
136              open (BIBFILE, $filename);
137              $entry = Text::BibTeX::Entry->new($filename, \*BIBFILE);
138
139              # newfangled IO::File thingy
140              $file = IO::File->new($filename);
141              $entry = Text::BibTeX::Entry->new($filename, $file);
142
143           But using a "Text::BibTeX::File" object is simpler and preferred:
144
145              $file  = Text::BibTeX::File->new($filename);
146              $entry = Text::BibTeX::Entry->new($file);
147
148           Returns the new object, unless SOURCE is supplied and
149           reading/parsing the entry fails (e.g., due to end of file) -- then
150           it returns false.
151
152           You may supply a reference to an option hash as first argument.
153           Supported options are:
154
155           BINMODE
156               Set the way Text::BibTeX deals with strings. By default it
157               manages strings as bytes. You can set BINMODE to 'utf-8' to get
158               NFC normalized
159
160               Text::BibTeX::Entry->new(
161                     { binmode => 'utf-8', normalization => 'NFD' },
162                     $file });
163
164           NORMALIZATION
165               UTF-8 strings and you can customise the normalization with the
166               NORMALIZATION option.
167
168       clone
169           Clone a Text::BibTeX::Entry object, returning the clone. This re-
170           uses the reference to any Text::BibTeX::Structure or
171           Text::BibTeX::File but copies everything else, so that the clone
172           can be modified apart from the original.
173
174       read (BIBFILE)
175           Reads and parses an entry from BIBFILE, which must be a
176           "Text::BibTeX::File" object (or descendant).  The next entry will
177           be read from the file associated with that object.
178
179           Returns the same as "parse" (or "parse_s"): false if no entry found
180           (e.g., at end-of-file), true otherwise.  To see if the parse itself
181           failed (due to errors in the input), call the "parse_ok" method.
182
183       parse (FILENAME, FILEHANDLE)
184           Reads and parses the next entry from FILEHANDLE.  (That is, it
185           scans the input until an '@' sign is seen, and then slurps up to
186           the next '@' sign.  Everything between the two '@' signs [including
187           the first one, but not the second one -- it's pushed back onto the
188           input stream for the next entry] is parsed as a BibTeX entry, with
189           the simultaneous construction of an abstract syntax tree [AST].
190           The AST is traversed to ferret out the most interesting
191           information, and this is stuffed into a Perl hash, which
192           coincidentally is the "Text::BibTeX::Entry" object you've been
193           tossing around.  But you don't need to know any of that -- I just
194           figured if you've read this far, you might want to know something
195           about the inner workings of this module.)
196
197           The success of the parse is stored internally so that you can later
198           query it with the "parse_ok" method.  Even in the presence of
199           syntax errors, you'll usually get something resembling your input,
200           but it's usually not wise to try to do anything with it.  Just call
201           "parse_ok", and if it returns false then silently skip to the next
202           entry.  (The error messages printed out by the parser should be
203           quite adequate for the user to figure out what's wrong.  And no,
204           there's currently no way for you to capture or redirect those error
205           messages -- they're always printed to "stderr" by the underlying C
206           code.  That should change in future releases.)
207
208           If no '@' signs are seen on the input before reaching end-of-file,
209           then we've exhausted all the entries in the file, and "parse"
210           returns a false value.  Otherwise, it returns a true value -- even
211           if there were syntax errors.  Hence, it's important to check
212           "parse_ok".
213
214           The FILENAME parameter is only used for generating error messages,
215           but anybody using your program will certainly appreciate your
216           setting it correctly!
217
218           Passing "undef" to FILEHANDLE will reset the state of the
219           underlying C parser, which is required in order to parse multiple
220           files.
221
222       parse_s (TEXT)
223           Parses a BibTeX entry (using the above rules) from the string TEXT.
224           The string is not modified; repeatedly calling "parse_s" with the
225           same string will give you the same results each time.  Thus,
226           there's no point in putting multiple entries in one string.
227
228           Passing "undef" to TEXT will reset the state of the underlying C
229           parser, which may be required in order to parse multiple strings.
230
231   Entry query methods
232       parse_ok ()
233           Returns false if there were any serious errors encountered while
234           parsing the entry.  (A "serious" error is a lexical or syntax
235           error; currently, warnings such as "undefined macro" result in an
236           error message being printed to "stderr" for the user's edification,
237           but no notice is available to the calling code.)
238
239       type ()
240           Returns the type of the entry.  (The `type' is the word that
241           follows the '@' sign; e.g. `article', `book', `inproceedings', etc.
242           for the standard BibTeX styles.)
243
244       metatype ()
245           Returns the metatype of the entry.  (The `metatype' is a numeric
246           value used to classify entry types into four groups: comment,
247           preamble, macro definition (@string entries), and regular (all
248           other entry types).  "Text::BibTeX" exports four constants for
249           these metatypes: "BTE_COMMENT", "BTE_PREAMBLE", "BTE_MACRODEF", and
250           "BTE_REGULAR".)
251
252       key ()
253           Returns the key of the entry.  (The key is the token immediately
254           following the opening `{' or `(' in "regular" entries.  Returns
255           "undef" for entries that don't have a key, such as macro definition
256           (@string) entries.)
257
258       num_fields ()
259           Returns the number of fields in the entry.  (Note that, currently,
260           this is not equivalent to putting "scalar" in front of a call to
261           "fieldlist".  See below for the consequences of calling "fieldlist"
262           in a scalar context.)
263
264       fieldlist ()
265           Returns the list of fields in the entry.
266
267           WARNING In scalar context, it no longer returns a reference to the
268           object's own list of fields.
269
270       exists (FIELD)
271           Returns true if a field named FIELD is present in the entry, false
272           otherwise.
273
274       get (FIELD, ...)
275           Returns the value of one or more FIELDs, as a list of values.  For
276           example:
277
278              $author = $entry->get ('author');
279              ($author, $editor) = $entry->get ('author', 'editor');
280
281           If a FIELD is not present in the entry, "undef" will be returned at
282           its place in the return list.  However, you can't completely trust
283           this as a test for presence or absence of a field; it is possible
284           for a field to be present but undefined.  Currently this can only
285           happen due to certain syntax errors in the input, or if you pass an
286           undefined value to "set", or if you create a new field with
287           "set_fieldlist" (the new field's value is implicitly set to
288           "undef").
289
290           Normally, the field value is what the input looks like after
291           "maximal processing"--quote characters are removed, whitespace is
292           collapsed (the same way that BibTeX itself does it), macros are
293           expanded, and multiple tokens are pasted together.  (See
294           bt_postprocess for details on the post-processing performed by
295           btparse.)
296
297           For example, if your input file has the following:
298
299              @string{of = "of"}
300              @string{foobars = "Foobars"}
301
302              @article{foobar,
303                title = {   The Mating Habits      } # of # " Adult   " # foobars
304              }
305
306           then using "get" to query the value of the "title" field from the
307           "foobar" entry would give the string "The Mating Habits of Adult
308           Foobars".
309
310           However, in certain circumstances you may wish to preserve the
311           values as they appear in the input.  This is done by setting a
312           "preserve_values" flag at some point; then, "get" will return not
313           strings but "Text::BibTeX::Value" objects.  Each "Value" object is
314           a list of "Text::BibTeX::SimpleValue" objects, which in turn
315           consists of a simple value type (string, macro, or number) and the
316           text of the simple value.  Various ways to set the
317           "preserve_values" flag and the interface to both "Value" and
318           "SimpleValue" objects are described in Text::BibTeX::Value.
319
320       value ()
321           Returns the single string associated with @comment and @preamble
322           entries.  For instance, the entry
323
324              @preamble{" This is   a preamble" #
325                        {---the concatenation of several strings}}
326
327           would return a value of "This is a preamble---the concatenation of
328           several strings".
329
330           If this entry was parsed in "value preservation" mode, then "value"
331           acts like "get", and returns a "Value" object rather than a simple
332           string.
333
334   Author name methods
335       This is the only part of the module that makes any assumption about the
336       nature of the data, namely that certain fields are lists delimited by a
337       simple word such as "and", and that the delimited sub-strings are human
338       names of the "First von Last" or "von Last, Jr., First" style used by
339       BibTeX.  If you are using this module for anything other than
340       bibliographic data, you can most likely forget about these two methods.
341       However, if you are in fact hacking on BibTeX-style bibliographic data,
342       these could come in very handy -- the name-parsing done by BibTeX is
343       not trivial, and the list-splitting would also be a pain to implement
344       in Perl because you have to pay attention to brace-depth.  (Not that it
345       wasn't a pain to implement in C -- it's just a lot more efficient than
346       a Perl implementation would be.)
347
348       Incidentally, both of these methods assume that the strings being split
349       have already been "collapsed" in the BibTeX way, i.e. all leading and
350       trailing whitespace removed and internal whitespace reduced to single
351       spaces.  This should always be the case when using these two methods on
352       a "Text::BibTeX::Entry" object, but these are actually just front ends
353       to more general functions in "Text::BibTeX".  (More general in that you
354       supply the string to be parsed, rather than supplying the name of an
355       entry field.)  Should you ever use those more general functions
356       directly, you might have to worry about collapsing whitespace; see
357       Text::BibTeX (the "split_list" and "split_name" functions in
358       particular) for more information.
359
360       Please note that the interface to author name parsing is experimental,
361       subject to change, and open to discussion.  Please let me know if you
362       have problems with it, think it's just perfect, or whatever.
363
364       split (FIELD [, DELIM [, DESC]])
365           Splits the value of FIELD on DELIM (default: `and').  Don't assume
366           that this works the same as Perl's builtin "split" just because the
367           names are the same: in particular, DELIM must be a simple string
368           (no regexps), and delimiters that are at the beginning or end of
369           the string, or at non-zero brace depth, or not surrounded by
370           whitespace, are ignored.  Some examples might illuminate matters:
371
372              if field F is...                then split (F) returns...
373              'Name1 and Name2'               ('Name1', 'Name2')
374              'Name1 and and Name2'           ('Name1', undef, 'Name2')
375              'Name1 and'                     ('Name1 and')
376              'and Name2'                     ('and Name2')
377              'Name1 {and} Name2 and Name3'   ('Name1 {and} Name2', 'Name3')
378              '{Name1 and Name2} and Name3'   ('{Name1 and Name2}', 'Name3')
379
380           Note that a warning will be issued for empty names (as in the
381           second example above).  A warning ought to be issued for delimiters
382           at the beginning or end of a string, but currently this isn't done.
383           (Hmmm.)
384
385           DESC is a one-word description of the substrings; it defaults to
386           'name'.  It is only used for generating warning messages.
387
388       names (FIELD)
389           Splits FIELD as described above, and further splits each name into
390           four components: first, von, last, and jr.
391
392           Returns a list of "Text::BibTeX::Name" objects, each of which
393           represents one name.  Use the "part" method to query these objects;
394           see Text::BibTeX::Name for details on the interface to name objects
395           (and on name-parsing as well).
396
397           For example if this entry:
398
399              @article{foo,
400                       author = {John Smith and
401                                 Hacker, J. Random and
402                                 Ludwig van Beethoven and
403                                 {Foo, Bar and Company}}}
404
405           has been parsed into a "Text::BibTeX::Entry" object $entry, then
406
407              @names = $entry->names ('author');
408
409           will put a list of "Text::BibTeX::Name" objects in @names.  These
410           can be queried individually as described in Text::BibTeX::Name; for
411           instance,
412
413              @last = $names[0]->part ('last');
414
415           would put the list of tokens comprising the last name of the first
416           author into the @last array: "('Smith')".
417
418   Entry modification methods
419       set_type (TYPE)
420           Sets the entry's type.
421
422       set_metatype (METATYPE)
423           Sets the entry's metatype (must be one of the four constants
424           "BTE_COMMENT", "BTE_PREAMBLE", "BTE_MACRODEF", and "BTE_REGULAR",
425           which are all optionally exported from "Text::BibTeX").
426
427       set_key (KEY)
428           Sets the entry's key.
429
430       set (FIELD, VALUE, ...)
431           Sets the value of field FIELD.  (VALUE might be "undef" or
432           unsupplied, in which case FIELD will simply be set to "undef" --
433           this is where the difference between the "exists" method and
434           testing the definedness of field values becomes clear.)
435
436           Multiple (FIELD, VALUE) pairs may be supplied; they will be
437           processed in order (i.e. the input is treated like a list, not a
438           hash).  For example:
439
440              $entry->set ('author', $author);
441              $entry->set ('author', $author, 'editor', $editor);
442
443           VALUE can be either a simple string or a "Text::BibTeX::Value"
444           object; it doesn't matter if the entry was parsed in "full post-
445           processing" or "preserve input values" mode.
446
447       delete (FIELD)
448           Deletes field FIELD from an entry.
449
450       set_fieldlist (FIELDLIST)
451           Sets the entry's list of fields to FIELDLIST, which must be a list
452           reference.  If any of the field names supplied in FIELDLIST are not
453           currently present in the entry, they are created with the value
454           "undef" and a warning is printed.  Conversely, if any of the fields
455           currently present in the entry are not named in the list of fields
456           supplied to "set_fields", they are deleted from the entry and
457           another warning is printed.
458
459   Entry output methods
460       write (BIBFILE)
461           Prints a BibTeX entry on the filehandle associated with BIBFILE
462           (which should be a "Text::BibTeX::File" object, opened for output).
463           Currently the printout is not particularly human-friendly; a highly
464           configurable pretty-printer will be developed eventually.
465
466       print (FILEHANDLE)
467           Prints a BibTeX entry on FILEHANDLE.
468
469       print_s ()
470           Prints a BibTeX entry to a string, which is the return value.
471
472   Miscellaneous methods
473       warn (WARNING [, FIELD])
474           Prepends a bit of location information (filename and line
475           number(s)) to WARNING, appends a newline, and passes it to Perl's
476           "warn".  If FIELD is supplied, the line number given is just that
477           of the field; otherwise, the range of lines for the whole entry is
478           given.  (Well, almost -- currently, the line number of the last
479           field is used as the last line of the whole entry.  This is a bug.)
480
481           For example, if lines 10-15 of file foo.bib look like this:
482
483              @article{homer97,
484                author = {Homer Simpson and Ned Flanders},
485                title = {Territorial Imperatives in Modern Suburbia},
486                journal = {Journal of Suburban Studies},
487                year = 1997
488              }
489
490           then, after parsing this entry to $entry, the calls
491
492              $entry->warn ('what a silly entry');
493              $entry->warn ('what a silly journal', 'journal');
494
495           would result in the following warnings being issued:
496
497              foo.bib, lines 10-14: what a silly entry
498              foo.bib, line 13: what a silly journal
499
500       line ([FIELD])
501           Returns the line number of FIELD.  If the entry was parsed from a
502           string, this still works--it's just the line number relative to the
503           start of the string.  If the entry was parsed from a file, this
504           works just as you'd expect it to: it returns the absolute line
505           number with respect to the whole file.  Line numbers are one-based.
506
507           If FIELD is not supplied, returns a two-element list containing the
508           line numbers of the beginning and end of the whole entry.
509           (Actually, the "end" line number is currently inaccurate: it's
510           really the the line number of the last field in the entry.  But
511           it's better than nothing.)
512
513       filename ()
514           Returns the name of the file from which the entry was parsed.  Only
515           works if the file is represented by a "Text::BibTeX::File"
516           object---if you just passed a filename/filehandle pair to "parse",
517           you can't get the filename back.  (Sorry.)
518

SEE ALSO

520       Text::BibTeX, Text::BibTeX::File, Text::BibTeX::Structure
521

AUTHOR

523       Greg Ward <gward@python.net>
524
526       Copyright (c) 1997-2000 by Gregory P. Ward.  All rights reserved.  This
527       file is part of the Text::BibTeX library.  This library is free
528       software; you may redistribute it and/or modify it under the same terms
529       as Perl itself.
530
531
532
533perl v5.30.0                      2019-07-26            Text::BibTeX::Entry(3)
Impressum