Text::...::Entry(3pm)

okay so this is Text::...::Entry(3pm) from the User Contributed Perl Documentation, and it’s all about Text::BibTeX::Entry β€” the module that reads and parses BibTeX files. Buckle up, bestie πŸ’…

🌸 NAME 🌸

Text::BibTeX::Entry β€” read and parse BibTeX files. That’s the whole vibe ✨

✨ SYNOPSIS ✨

use Text::BibTeX::Entry;

# ...assuming that $bibfile and $newbib are both objects of class
# Text::BibTeX::File, opened for reading and writing (respectively):

# Entry creation/parsing methods:
$entry = Text::BibTeX::Entry->new();
$entry->read ($bibfile);
$entry->parse ($filename, $filehandle);
$entry->parse_s ($entry_text);

# or:
$entry = Text::BibTeX::Entry->new( $bibfile );
$entry = Text::BibTeX::Entry->new( $filename, $filehandle );
$entry = Text::BibTeX::Entry->new( $entry_text );

# Entry query methods
warn "error in input" unless $entry->parse_ok;
$metatype = $entry->metatype;
$type = $entry->type;

# if metatype is BTE_REGULAR or BTE_MACRODEF:
$key = $entry->key;                  # only for BTE_REGULAR metatype
$num_fields = $entry->num_fields;
@fieldlist = $entry->fieldlist;
$has_title = $entry->exists ('title');
$title = $entry->get ('title');
# or:
($val1,$val2,...$valn) = $entry->get ($field1, $field2, ..., $fieldn);

# if metatype is BTE_COMMENT or BTE_PREAMBLE:
$value = $entry->value;

# Author name methods
@authors = $entry->split ('author');
($first_author) = $entry->names ('author');

# Entry modification methods
$entry->set_type ($new_type);
$entry->set_key ($new_key);
$entry->set ('title', $new_title);
# or:
$entry->set ($field1, $val1, $field2, $val2, ..., $fieldn, $valn);
$entry->delete (@fields);
$entry->set_fieldlist (\@fieldlist);

# Entry output methods
$entry->write ($newbib);
$entry->print ($filehandle);
$entry_text = $entry->print_s;

# Reset internal parser state:
$entry = Text::BibTeX::Entry->new();
$entry->parse ($filename, undef);
$entry->parse_s (undef);

# or:
$entry = Text::BibTeX::Entry->new( $filename, undef );
$entry = Text::BibTeX::Entry->new( undef );

# Miscellaneous methods
$entry->warn ($entry_warning);
# or:
$entry->warn ($field_warning, $field);
$entry->clone;

πŸ’– DESCRIPTION πŸ’–

So Text::BibTeX::Entry does all the real work of reading and parsing BibTeX files. (Well, actually it just provides an object-oriented Perl front-end to a C library that does all that. But that’s not important right now 😌)

BibTeX entries can be read either from Text::BibTeX::File objects using the read method, or directly from a filehandle using the parse method, or from a string using parse_s. The first one is preferable, because you don’t have to worry about supplying the filename, and because of the extra functionality provided by the Text::BibTeX::File class. Currently, this means you may specify the database structure to which entries are expected to conform via the File class. That lets you ensure entries follow the rules for required fields and mutually constrained fields for a particular type of database, and also gives you access to all the methods of the structured entry class for this database structure. See Text::BibTeX::Structure for details on database structures πŸ‘‘

Once you have the entry, you can query it or change it in a variety of ways. The query methods are parse_ok, type, key, num_fields, fieldlist, exists, and get. The methods for changing the entry are set_type, set_key, set_fieldlist, delete, and set.

Finally, you can output BibTeX entries, again either to an open Text::BibTeX::File object, a filehandle, or a string. (A filehandle or File object must, of course, have been opened in write mode.) Output to a File object is done with the write method, to a filehandle via print, and to a string with print_s. Using the File class is recommended for future extensibility, although it currently doesn’t offer anything extra πŸ¦‹

πŸŽ€ METHODS πŸŽ€

πŸ¦‹ Entry creation/parsing methods πŸ¦‹

πŸ’… new ([OPTS ,] [SOURCE]) πŸ’…

Creates a new Text::BibTeX::Entry object. If the SOURCE parameter is supplied, it must be one of the following: a Text::BibTeX::File (or descendant class) object, a filename/filehandle pair, or a string. Calls read to read from a Text::BibTeX::File object, parse to read from a filehandle, and parse_s to read from a string.

A filehandle can be specified as a GLOB reference, or as an IO::Handle (or descendants) object, or as a FileHandle (or descendants) object. (But there’s really no point in using FileHandle objects, since Text::BibTeX requires Perl 5.004, which always includes the IO modules.) You can not pass in the name of a filehandle as a string, though, because Text::BibTeX::Entry conforms to the use strict pragma (which disallows such symbolic references) 🚫

The corresponding filename should be supplied in order to allow for accurate error messages; if you simply don’t have the filename, you can pass undef and you’ll get error messages without a filename. (It’s probably better to rearrange your code so that the filename is available, though.)

Thus, the following are equivalent to read from a file named by $filename (error handling ignored):

# good ol' fashioned filehandle and GLOB ref
open (BIBFILE, $filename);
$entry = Text::BibTeX::Entry->new($filename, \*BIBFILE);

# newfangled IO::File thingy
$file = IO::File->new($filename);
$entry = Text::BibTeX::Entry->new($filename, $file);

But using a Text::BibTeX::File object is simpler and preferred:

$file  = Text::BibTeX::File->new($filename);
$entry = Text::BibTeX::Entry->new($file);

Returns the new object, unless SOURCE is supplied and reading/parsing the entry fails (e.g., due to end of file) β€” then it returns false 😭

You may supply a reference to an option hash as first argument. Supported options are:

  • BINMODE β€” set the way Text::BibTeX deals with strings. By default it manages strings as bytes. You can set BINMODE to 'utf-8' to get NFC normalized
Text::BibTeX::Entry->new(
      { binmode => 'utf-8', normalization => 'NFD' },
      $file });
  • NORMALIZATION β€” UTF-8 strings and you can customise the normalization with the NORMALIZATION option.

πŸ’… clone πŸ’…

Clone a Text::BibTeX::Entry object, returning the clone. This re-uses the reference to any Text::BibTeX::Structure or Text::BibTeX::File but copies everything else, so that the clone can be modified apart from the original. It’s giving β€œtwin but make it independent” πŸ‘―β€β™€οΈ

πŸ’… read (BIBFILE) πŸ’…

Reads and parses an entry from BIBFILE, which must be a Text::BibTeX::File object (or descendant). The next entry will be read from the file associated with that object.

Returns the same as parse (or parse_s): false if no entry found (e.g., at end-of-file), true otherwise. To see if the parse itself failed (due to errors in the input), call the parse_ok method 😌

πŸ’… parse (FILENAME, FILEHANDLE) πŸ’…

Reads and parses the next entry from FILEHANDLE. (That is, it scans the input until an '@' sign is seen, and then slurps up to the next '@' sign. Everything between the two '@' signs [including the first one, but not the second one β€” it’s pushed back onto the input stream for the next entry] is parsed as a BibTeX entry, with the simultaneous construction of an abstract syntax tree [AST]. The AST is traversed to ferret out the most interesting information, and this is stuffed into a Perl hash, which coincidentally is the Text::BibTeX::Entry object you’ve been tossing around. But you don’t need to know any of that β€” I just figured if you’ve read this far, you might want to know something about the inner workings of this module.) 🧚

The success of the parse is stored internally so that you can later query it with the parse_ok method. Even in the presence of syntax errors, you’ll usually get something resembling your input, but it’s usually not wise to try to do anything with it. Just call parse_ok, and if it returns false then silently skip to the next entry. (The error messages printed out by the parser should be quite adequate for the user to figure out what’s wrong. And no, there’s currently no way for you to capture or redirect those error messages β€” they’re always printed to stderr by the underlying C code. That should change in future releases.)

If no '@' signs are seen on the input before reaching end-of-file, then we’ve exhausted all the entries in the file, and parse returns a false value. Otherwise, it returns a true value β€” even if there were syntax errors. Hence, it’s important to check parse_ok ⚠️

The FILENAME parameter is only used for generating error messages, but anybody using your program will certainly appreciate your setting it correctly! πŸ’–

Passing undef to FILEHANDLE will reset the state of the underlying C parser, which is required in order to parse multiple files πŸ”

πŸ’… parse_s (TEXT) πŸ’…

Parses a BibTeX entry (using the above rules) from the string TEXT. The string is not modified; repeatedly calling parse_s with the same string will give you the same results each time. Thus, there’s no point in putting multiple entries in one string.

Passing undef to TEXT will reset the state of the underlying C parser, which may be required in order to parse multiple strings 🌈

🌈 Entry query methods 🌈

πŸ’… parse_ok () πŸ’…

Returns false if there were any serious errors encountered while parsing the entry. (A β€œserious” error is a lexical or syntax error; currently, warnings such as β€œundefined macro” result in an error message being printed to stderr for the user’s edification, but no notice is available to the calling code.) πŸ’€

πŸ’… type () πŸ’…

Returns the type of the entry. (The type is the word that follows the '@' sign; e.g. article, book, inproceedings, etc. for the standard BibTeX styles.)

πŸ’… metatype () πŸ’…

Returns the metatype of the entry. (The metatype is a numeric value used to classify entry types into four groups: comment, preamble, macro definition (@string entries), and regular (all other entry types). Text::BibTeX exports four constants for these metatypes: BTE_COMMENT, BTE_PREAMBLE, BTE_MACRODEF, and BTE_REGULAR.) πŸ‘‘

  • key () β€” hands you the entry's key, bestie. πŸ’… (Quick refresher: the key is the token right after the opening { or ( in "regular" entries.) Returns undef for entries that don't even have a key, like macro definition (@string) entries β€” yes, they're keyless icons and that's valid.
  • num_fields () β€” the number of fields in the entry. Small heads-up though: right now this is not the same as slapping scalar in front of a fieldlist call. Scroll down to see the whole saga of calling fieldlist in scalar context. πŸ‘€
  • fieldlist () β€” returns the list of fields in the entry.
WARNING ⚠️ in scalar context it no longer returns a reference to the object's own list of fields. That era is over, bestie.
  • exists (FIELD) β€” true if a field named FIELD is in the entry, false otherwise. That's it, that's the vibe check. ✨
  • get (FIELD, ...) β€” returns the value of one or more FIELDs, as a list of values. Like:
$author = $entry->get ('author');
($author, $editor) = $entry->get ('author', 'editor');

If a FIELD isn't in the entry, undef comes back in its spot in the return list. But β€” and this is so important β€” you can't fully trust that as a test for whether a field is there or not, because a field can totally be present and still be undef. Currently that only happens with certain syntax errors in the input, or if you pass an undefined value to set, or if you create a new field with set_fieldlist (the new field's value gets implicitly set to undef). Messy, but now you know. πŸ’€

Normally, the field value is what the input looks like after "maximal processing" β€” quote characters removed, whitespace collapsed the exact same way BibTeX itself does it, macros expanded, and multiple tokens pasted together. (Peep bt_postprocess if you want the fine print on the post-processing btparse performs.)

So like, if your input file has this:

@string{of = "of"}
@string{foobars = "Foobars"}

@article{foobar,
  title = {   The Mating Habits      } # of # " Adult   " # foobars
}

then using get to query the value of the title field from the foobar entry gives you the string The Mating Habits of Adult Foobars. Slay, concatenation ate. πŸ”₯

But sometimes you want to preserve the values exactly how they appear in the input, right? That's what the preserve_values flag is for β€” set it and get stops returning strings and starts returning Text::BibTeX::Value objects. Each Value object is a list of Text::BibTeX::SimpleValue objects, and each of those is a simple value type (string, macro, or number) plus the text of the simple value. All the ways to set that preserve_values flag and the full interface for both Value and SimpleValue objects live in Text::BibTeX::Value. πŸ¦‹

  • value () β€” returns the single string associated with @comment and @preamble entries. For instance, this entry:
@preamble{" This is   a preamble" #
          {---the concatenation of several strings}}

would give you back a value of This is a preamble---the concatenation of several strings. ✨

And if this entry got parsed in "value preservation" mode, then value acts just like get and returns a Value object instead of a plain little string. πŸŽ€


🧚 Author name methods 🧚

Okay so this is literally the only part of the module that assumes anything about the nature of the data β€” specifically that certain fields are lists delimited by a simple word like and, and that the delimited sub-strings are human names in the "First von Last" style or the "von Last, Jr., First" style that BibTeX uses. If you're using this module for anything that isn't bibliographic data, you can most likely just forget these two methods exist. πŸ’…

But if you are out here hacking on BibTeX-style bibliographic data, these are lowkey a lifesaver β€” the name-parsing BibTeX does is not trivial, and the list-splitting would be such a pain to implement in Perl because you have to keep track of brace-depth. (Not that it wasn't a pain in C β€” it's just way more efficient than a Perl implementation would be. 😭)

Fun fact, both of these methods assume the strings being split have already been "collapsed" the BibTeX way, i.e. all leading and trailing whitespace removed and internal whitespace reduced to single spaces. That should always be the case when you use these two on a Text::BibTeX::Entry object, but just so you know, these are actually front ends to more general functions in Text::BibTeX. (More general meaning you supply the string to be parsed, instead of supplying the name of an entry field.) If you ever use those more general functions directly, you might have to worry about collapsing whitespace β€” check Text::BibTeX, especially the split_list and split_name functions, for more. πŸ“–

Heads up bestie: the interface to author name parsing is experimental, subject to change, and open to discussion. Please let the author know if you have problems with it, think it's just perfect, or whatever. 🫢
  • split (FIELD [, DELIM [, DESC]]) β€” splits the value of FIELD on DELIM (default: and). Do not assume this works like Perl's builtin split just because the names match β€” in particular, DELIM has to be a simple string (no regexps!), and delimiters at the beginning or end of the string, or at non-zero brace depth, or not surrounded by whitespace, are just ignored. Some examples might illuminate matters:
if field F is...                then split (F) returns...
'Name1 and Name2'               ('Name1', 'Name2')
'Name1 and and Name2'           ('Name1', undef, 'Name2')
'Name1 and'                     ('Name1 and')
'and Name2'                     ('and Name2')
'Name1 {and} Name2 and Name3'   ('Name1 {and} Name2', 'Name3')
'{Name1 and Name2} and Name3'   ('{Name1 and Name2}', 'Name3')

Note that a warning gets issued for empty names (see the second example above). A warning ought to be issued for delimiters at the beginning or end of a string, but currently that isn't done. (Hmmm. πŸ™ˆ)

DESC is a one-word description of the substrings; it defaults to name. It's only used for generating warning messages.

  • names (FIELD) β€” splits FIELD as described above, then further splits each name into four components: first, von, last, and jr. πŸŽ€

Returns a list of Text::BibTeX::Name objects, each one representing a single name. Use the part method to query these objects β€” see Text::BibTeX::Name for the details on the interface to name objects (and on name-parsing too).

For example, if this entry:

@article{foo,
         author = {John Smith and
                   Hacker, J. Random and
                   Ludwig van Beethoven and
                   {Foo, Bar and Company}}}

has been parsed into a Text::BibTeX::Entry object $entry, then

@names = $entry->names ('author');

puts a list of Text::BibTeX::Name objects in @names. You can query them individually as described in Text::BibTeX::Name β€” for instance,

@last = $names[0]->part ('last');

would put the list of tokens comprising the last name of the first author into the @last array: ('Smith'). Iconic. πŸ’–


🌈 Entry modification methods 🌈

  • set_type (TYPE) β€” sets the entry's type.
  • set_metatype (METATYPE) β€” sets the entry's metatype. It must be one of the four constants BTE_COMMENT, BTE_PREAMBLE, BTE_MACRODEF, and BTE_REGULAR, which are all optionally exported from Text::BibTeX. πŸ‘‘
  • set_key (KEY) β€” sets the entry's key.
  • set (FIELD, VALUE, ...) β€” sets the value of field FIELD. (VALUE might be undef or not supplied at all, in which case FIELD just gets set to undef β€” and this is exactly where the difference between the exists method and testing the definedness of field values becomes crystal clear, bestie.)

Multiple (FIELD, VALUE) pairs can be supplied; they get processed in order (i.e. the input is treated like a list, not a hash). For example:

$entry->set ('author', $author);
$entry->set ('author', $author, 'editor', $editor);

VALUE can be either a simple string or a Text::BibTeX::Value object β€” doesn't matter whether the entry was parsed in "full post-processing" or "preserve input values" mode. πŸ¦‹

  • delete (FIELD) β€” deletes field FIELD from an entry. bye bestie πŸ‘‹
  • set_fieldlist (FIELDLIST) β€” sets the entry's list of fields to FIELDLIST, which must be a list reference. If any of the field names supplied in FIELDLIST aren't currently present in the entry, they get created with the value undef and a warning is printed. Conversely, if any of the fields currently present in the entry aren't named in the list of fields supplied to set_fields (yep, that's set_fields exactly how the page writes it β€” go figure πŸ’€), they get deleted from the entry and another warning is printed.

⭐ Entry output methods ⭐

  • write (BIBFILE) β€” prints a BibTeX entry on the filehandle associated with BIBFILE (which should be a Text::BibTeX::File object, opened for output). Currently the printout is not particularly human-friendly; a highly configurable pretty-printer will be developed eventually. patience, bestie 🧚
  • print (FILEHANDLE) β€” prints a BibTeX entry on FILEHANDLE.
  • print_s () β€” prints a BibTeX entry to a string, which is the return value. πŸŽ€

πŸ“ Miscellaneous methods πŸ“

  • warn (WARNING [, FIELD]) β€” prepends a bit of location info (filename and line number(s)) to WARNING, appends a newline, and passes it to Perl's warn. If FIELD is supplied, the line number given is just that of the field; otherwise the range of lines for the whole entry is given. (Well, almost β€” currently the line number of the last field is used as the last line of the whole entry. That's a bug. πŸ’€)

For example, if lines 10-15 of file foo.bib look like this:

@article{homer97,
  author = {Homer Simpson and Ned Flanders},
  title = {Territorial Imperatives in Modern Suburbia},
  journal = {Journal of Suburban Studies},
  year = 1997
}

then, after parsing this entry to $entry, the calls

$entry->warn ('what a silly entry');
$entry->warn ('what a silly journal', 'journal');

would result in the following warnings being issued:

foo.bib, lines 10-14: what a silly entry
foo.bib, line 13: what a silly journal

(Yes, 10-14 β€” that's the bug we just mentioned doing its thing. 😭)

πŸ’… line ([FIELD]) β€” the receipts method

Returns the line number of FIELD. Bestie, and here's the cute part: if the entry was parsed from a string, this still works β€” it's just the line number relative to the start of the string. If the entry was parsed from a file, it works just as you'd expect it to: it returns the absolute line number with respect to the whole file. Line numbers are one-based (so the first line is line 1, not line 0, we're not monsters 🫢).

If FIELD is not supplied, it returns a two-element list containing the line numbers of the beginning and end of the whole entry.

Real talk though 😭 β€” the "end" line number is currently inaccurate: it's really the line number of the last field in the entry. But it's better than nothing. πŸ’€

πŸŽ€ filename () β€” who's your file parent

Returns the name of the file from which the entry was parsed.

Only works if the file is represented by a Text::BibTeX::File object β€” if you just passed a filename/filehandle pair to parse, you can't get the filename back. (Sorry.) πŸ™ˆ


πŸ¦‹ SEE ALSO

  • Text::BibTeX
  • Text::BibTeX::File
  • Text::BibTeX::Structure

πŸ‘‘ AUTHOR

Greg Ward <gward@python.net>


Copyright (c) 1997-2000 by Gregory P. Ward. All rights reserved.

This file is part of the Text::BibTeX library. This library is free software; you may redistribute it and/or modify it under the same terms as Perl itself.


✨ And that's the whole page, bestie β€” perl v5.42.0, dated 2025-01-31, doc'd as Text::...::Entry(3pm). You ate that honestly πŸ’– mwah πŸŽ€

πŸ“¦ where this page comes from